我正在尝试使用Android共享首选项来保存某些应用程序值
这是我的onCreate的代码:

protected void onCreate(Bundle savedInstanceState) {

    SharedPreferences preferences = getSharedPreferences("MyPref", MODE_PRIVATE);
    boolean firstLaunch = preferences.getBoolean("firstlaunch", true);

    System.out.println("FIRST LAUNCH? " + firstLaunch);

    if(firstLaunch == true){
        SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
        editor.putString("language", "en");
        editor.putInt("theme", R.style.Default);
        editor.putBoolean("firstLaunch", false);
        editor.commit();
        System.out.println("FIRST LAUNCH:" + preferences.getBoolean("firstLaunch", true));
    }


重新启动应用程序时,firstLaunch是否仍然正确?为什么是这样?

最佳答案

您有个案问题。
firstlaunchfirstLaunch

为避免此类问题,您应该使用静态成员。

private static final String KEY_PREFS_NAME = "myPrefs";
private static final String KEY_FIRST_LAUNCH = "firstLaunch";

protected void onCreate(Bundle savedInstanceState) {

SharedPreferences preferences = getSharedPreferences(KEY_PREFS_NAME, MODE_PRIVATE);
boolean firstLaunch = preferences.getBoolean(KEY_FIRST_LAUNCH, true);

System.out.println("FIRST LAUNCH? " + firstLaunch);

if(firstLaunch == true){
    SharedPreferences.Editor editor = getSharedPreferences(KEY_PREFS_NAME, MODE_PRIVATE).edit();
    editor.putString("language", "en");
    editor.putInt("theme", R.style.Default);
    editor.putBoolean(KEY_FIRST_LAUNCH, false);
    editor.commit();
    System.out.println("FIRST LAUNCH:" + preferences.getBoolean(KEY_FIRST_LAUNCH, true));
}

07-27 15:58