I am trying to implement sessions (shared Preferences) with my sqlite database.
I have Username and Password fields that I'd like to save to shared preferences. However, I only want to do this if the login is valid.
If it is valid login, sign in the user (go to next activity as specified) and save it in the shared preferences. This is my goal; however, I am having trouble implementing this.
Here is my code:
package com.example.votingapp;
import com.example.votingapp.library.DatabaseHandler;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText inputUserName;
EditText inputUserPass;
Button btnLogin;
Button btnRegister;
DatabaseHandler database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setting default screen to activity_main.xml
setContentView(R.layout.activity_main);
//Importing all assets like buttons, text fields
inputUserName = (EditText) findViewById(R.id.UserName);
inputUserPass = (EditText) findViewById(R.id.UserPass);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.btnRegister);
//SharedPreferences
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
String username = settings.getString("username", null);
String password = settings.getString("password", null);
if(!(username==null) && !(password==null)){
Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
startActivity(dashboard);
finish();
}
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName = inputUserName.getText().toString();
String userPass = inputUserPass.getText().toString();
boolean validLogin = validateLogin(userName, userPass, MainActivity.this);
//SharedPreferences
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
SharedPreferences.Editor editor = settings.edit();
if(validLogin){
editor.putString("username", userName);
editor.putString("password", userPass);
editor.commit();
}else{
inputUserName.setText(settings.getString("username", ""));
inputUserPass.setText(settings.getString("password", ""));
}
if(userName.equals("") || userName == null){
Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
}else if(userPass.equals("") || userPass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
if(validLogin){
//Show a dialog of login successful
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
//Close views before starting Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}
}
}
});//Login Button On SetListener
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent Register = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(Register);
finish();
}
});//Register Button onClickListener
}//On Create
public boolean validateLogin(String userName, String userPass, Context context) {
DatabaseHandler database = new DatabaseHandler(getApplicationContext());
SQLiteDatabase db = database.getReadableDatabase();
//SELECT
String[] columns = {"userId"};
//WHERE clause
String selection = "userName=? AND userPass=?";
//WHERE clause arguments
String[] selectionArgs = {userName, userPass};
Cursor c = null;
try{
//SELECT userId FROM login WHERE username=userName AND password=userPass
c = db.query(DatabaseHandler.TABLE_USERS, columns, selection, selectionArgs, null, null, null);
c.moveToFirst();
c.close();
}catch(Exception e){
e.printStackTrace();
}
int i = c.getCount();
if(i <= 0){
Toast.makeText(getApplicationContext(), "Incorrect Login..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}//validate Login
}//Mainactivity
you are not storing username and password of text field to SharedPreferences but your code store null value to sharedPreferences. Try this code
package com.example.votingapp;
import com.example.votingapp.library.DatabaseHandler;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText inputUserName;
EditText inputUserPass;
Button btnLogin;
Button btnRegister;
DatabaseHandler database;
SharedPreferences sp;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setting default screen to activity_main.xml
setContentView(R.layout.activity_main);
//Importing all assets like buttons, text fields
inputUserName = (EditText) findViewById(R.id.UserName);
inputUserPass = (EditText) findViewById(R.id.UserPass);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName = inputUserName.getText().toString();
String userPass = inputUserPass.getText().toString();
if(userName.equals("") || userName == null){
Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
}else if(userPass.equals("") || userPass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(userName, userPass, MainActivity.this);
if(validLogin){
//SharedPreferences
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
inputUserName.setText(settings.getString("username", ""));
inputUserPass.setText(settings.getString("password", ""));
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", userName);
editor.putString("password", userPass);
editor.commit();
String username = settings.getString("username", null);
String password = settings.getString("password", null);
if(!(username==null) && !(password==null)){
Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
startActivity(dashboard);
finish();
}
//Show a dialog of login successful
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
//Close views before starting Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}
}
}
});//Login Button On SetListener
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent Register = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(Register);
finish();
}
});//Register Button onClickListener
}//On Create
public boolean validateLogin(String userName, String userPass, Context context) {
DatabaseHandler database = new DatabaseHandler(getApplicationContext());
SQLiteDatabase db = database.getReadableDatabase();
//SELECT
String[] columns = {"userId"};
//WHERE clause
String selection = "userName=? AND userPass=?";
//WHERE clause arguments
String[] selectionArgs = {userName, userPass};
Cursor c = null;
try{
//SELECT userId FROM login WHERE username=userName AND password=userPass
c = db.query(DatabaseHandler.TABLE_USERS, columns, selection, selectionArgs, null, null, null);
c.moveToFirst();
c.close();
}catch(Exception e){
e.printStackTrace();
}
int i = c.getCount();
if(i <= 0){
Toast.makeText(getApplicationContext(), "Incorrect Login..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}//validate Login
}//Mainactivity
而不是存储的UserName
和Password
的数据库,你可以使用SharedPreferences
存储它像这样
In ValidateLogin(), You are closing cursor and after closing it, you are calling cursor.getCount(). It is wrong. Check my edited code.
package com.example.votingapp;
import com.example.votingapp.library.DatabaseHandler;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText inputUserName;
EditText inputUserPass;
Button btnLogin;
Button btnRegister;
DatabaseHandler database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setting default screen to activity_main.xml
setContentView(R.layout.activity_main);
//Importing all assets like buttons, text fields
inputUserName = (EditText) findViewById(R.id.UserName);
inputUserPass = (EditText) findViewById(R.id.UserPass);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.btnRegister);
//SharedPreferences
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
String username = settings.getString("username", null);
String password = settings.getString("password", null);
if(username!=null && password!=null){
Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
startActivity(dashboard);
finish();
}
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName = inputUserName.getText().toString();
String userPass = inputUserPass.getText().toString();
boolean validLogin = validateLogin(userName, userPass, MainActivity.this);
if(validLogin){
//SharedPreferences
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", userName);
editor.putString("password", userPass);
editor.commit();
}else{
inputUserName.setText(settings.getString("username", ""));
inputUserPass.setText(settings.getString("password", ""));
}
if(userName.equals("") || userName == null){
Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
}else if(userPass.equals("") || userPass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
if(validLogin){
//Show a dialog of login successful
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
//Close views before starting Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}
}
}
});//Login Button On SetListener
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent Register = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(Register);
finish();
}
});//Register Button onClickListener
}//On Create
public boolean validateLogin(String userName, String userPass, Context context) {
DatabaseHandler database = new DatabaseHandler(getApplicationContext());
SQLiteDatabase db = database.getReadableDatabase();
//SELECT
String[] columns = {"userId"};
//WHERE clause
String selection = "userName=? AND userPass=?";
//WHERE clause arguments
String[] selectionArgs = {userName, userPass};
Cursor c = null;
try{
//SELECT userId FROM login WHERE username=userName AND password=userPass
c = db.query(DatabaseHandler.TABLE_USERS, columns, selection, selectionArgs, null, null, null);
c.moveToFirst();
int i = c.getCount();
c.close();
if(i <= 0){
Toast.makeText(getApplicationContext(), "Incorrect Login..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}//validate Login
}//Mainactivity
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.