0

我有这个代码:

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。

在同一个活动的某个地方,我得到了相同的编辑代码,它工作正常,但唯一的区别是我从来没有在它被编辑后立即使用它,我在再次调用活动时使用它。

4

1 回答 1

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 + "");
    }
}
于 2012-06-08T05:38:20.300 回答