I have two activities LoginActivity
and MainActivity
, I authenticate my user from the LoginActivity
. If the user was authenticated successfully, I call startActivity() with the MainActivity
intent. This is what the LoginActivity
looks like:
In my onCreate()
I initialised my SharedPreferences objects which had been declared as fields of the class:
userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = userInfo.edit();
Then I handle authentication logic in the login()
method:
private void login() {
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
final String email = emailText.getText().toString();
final String password = passwordText.getText().toString();
new android.os.Handler().postDelayed(new Runnable() {
public void run() {
ref.authWithPassword(email, password, new Firebase.AuthResultHandler({
// User was authenticated successfully
@Override
public void onAuthenticated(AuthData authData) {
@Override
public void onDataChange(DataSnapshot snapshot) {
UserSchema user = snapshot.getValue(UserSchema.class);
// store the user's name and email with our SharedPreferences
editor.putString("name", user.getName());
editor.putString("email", user.getEmail());
editor.apply();
}
});
// Dismiss the progress dialog shown while authenticating the user
progressDialog.dismiss();
// Start the MainActivity
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}, 3000);
}
I am also initialising the PreferenceManager in the MainActivity's onCreate()
:
userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Everything works fine at first but when the MainActivity
starts, all calls to get the user's info that was stored returns with the default values I had set in the MainActivity
class:
// returns the default value at first
String s1 = userInfo.getString("name", "name");
String s2 = userInfo.getString("email", "email");
Weird part: If I close the app from my device's recents and relaunch it, the right values of the user's name and email show up correctly.