Reputation: 125
When I click on the 'remember me' checkbox, based on the codes it will save the username and password by sharepreferences
. However, when I exit my application and go back, the username and password will disappear.
How do I save the username and password between sessions?
// Remember me function
CheckBox cbRemember = (CheckBox) findViewById(R.id.chkRememberPassword);
if (cbRemember.isChecked()) {
// save username & password
SharedPreferences mySharedPreferences = getSharedPreferences(
"PREFS", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("UserName",
String.valueOf(txtLogin.getText().toString()));
editor.putString("Password",
String.valueOf(txtPassword.getText().toString()));
editor.commit();
}
Upvotes: 1
Views: 398
Reputation: 4842
When you exit the app and go back, the onResume()
method will be called. It's the place where you should put Paresh Mayani's codes to retrieve the username and password. Check here to understand the lifecycle of an activity in Android.
Upvotes: 0
Reputation: 128428
Same as you have put username and password strings inside the shared preference, you can retrieve the same by doing as below:
SharedPreferences settings = getSharedPreferences("PREFS",0);
settings.getString("UserName", "");
settings.getString("user", "");
But i think for implementing remember me functionality, just put a boolean flag whenever the login is successful:
editor.putBoolean("login",true);
and retrieve whenever app is re-started next time:
settings.getBoolean("login", false);
Upvotes: 1
Reputation: 1939
I think the problem is with the Activity.MODE_PRIVATE flag use instead getSharedPreferences("PREFS", MODE_WORLD_WRITEABLE) flag.
Upvotes: 0