So basically I have an activity (SplashActivity
) that serves as a splash screen. It reads a key named username
from the application's SharedPreferences
, then if it finds the key, starts HomePage
activity. Otherwise it starts LoginActivity
. When the login is successful in LoginActivity
, I am storing the username and password via this code:
SharedPreferences prefs = LoginActivity.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
The login page also has an autocomplete feature for the password field. This is how I am reading the password:
String password = this.getPreferences(MODE_PRIVATE).getString("password", "");
And I get the stored password. However, when I restart the app and run SplashActivity
I can't read the password despite using the exact same code as above. Is there something wrong I am doing here?
Quoting the JavaDocs for getPreferences()
:
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.
(emphasis added)
So, SplashActivity
cannot read a value written to the private preferences of LoginActivity
.
You probably want to switch to getSharedPreferences()
, where you provide your own name that can be shared between the two activities.