我有这段代码:
public static final String PREFS_NAME = "MyPrefsFile";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if (!((LoginButton.email).equals(""))) {
//settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
// Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
Log.d("hasLoggedIn in email check = ", hasLoggedIn + "");
}
}
即使在输入if之后,最后一个Log也将hadLoggedIn视为false。
在同一个活动的某个地方,我得到了相同的编辑代码,但是唯一的区别是我从未在编辑时使用它,我在再次调用活动时使用它。
答案 0 :(得分:1)
您将再次打开共享偏好进行阅读。
您的hasLoggedIn仍包含旧值。
我已更新您的代码,如下所示。
public static final String PREFS_NAME = "MyPrefsFile";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if (!((LoginButton.email).equals(""))) {
//settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
// Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
//You forgot write following line.
hasLoggedIn = getSharedPreferences(PREFS_NAME, 0).getBoolean("hasLoggedIn", false);
Log.d("hasLoggedIn in email check = ", hasLoggedIn + "");
}
}