![](/img/trans.png)
[英]ANDROID JAVA: Activity doesn't start when the used SharedPreferences
[英]Why doesn't my SharedPreferences retrieve the right data when I start a new Activity?
我有兩個活動LoginActivity
和MainActivity
,我從LoginActivity
驗證我的用戶。 如果用戶已成功通過身份驗證,則可以使用MainActivity
意圖調用startActivity()。 這是LoginActivity
樣子:
在我的onCreate()
,初始化了我的SharedPreferences對象,該對象已聲明為該類的字段:
userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = userInfo.edit();
然后,我在login()
方法中處理身份驗證邏輯:
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);
}
我也在MainActivity的onCreate()
初始化PreferenceManager:
userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
最初一切都很好,但是當MainActivity
啟動時,所有用於獲取存儲的用戶信息的調用都將返回我在MainActivity
類中設置的默認值:
// returns the default value at first
String s1 = userInfo.getString("name", "name");
String s2 = userInfo.getString("email", "email");
怪異的部分:如果我從設備的最新版本中關閉該應用程序並重新啟動,則正確顯示了用戶名和電子郵件的正確值。
請注意, onDataChange
是一個回調,不會立即被調用,但是在點擊此回調之前將調用startActivity
。 因此,在將數據保存到SharedPreference
之前,將調用MainActivity
。
代碼應該是這樣的
private void login() {
...
// User was authenticated successfully
@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();
// Start the MainActivity
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
我不確定,但是嘗試使用editor.commit();
而不是editor.apply();
因為使用commit可以立即存儲數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.