SharedPreferences.edit()没有相应的commit()或apply()调用

时间:2017-02-07 14:45:54

标签: android sharedpreferences

我在我的应用中使用SharedPreferences'简介滑块。但是,我在这一行收到错误:

class PrefManager {
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;


    private static final String PREF_NAME = "welcome";

    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    PrefManager(Context context) {
        int PRIVATE_MODE = 0;
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.commit();
    }

    boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }

}
  

editor = pref.edit();

如果我在调用edit()后没有调用commit()或apply()会怎样?

4 个答案:

答案 0 :(得分:4)

  

如果我在调用edit()后没有调用commit()或apply()会怎样?

没有

答案 1 :(得分:4)

简单方法

 sharedPreferences = getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                boolean firstTime = sharedPreferences.getBoolean("first", true);
                if (firstTime) {
                    editor.putBoolean("first", false);
                    //For commit the changes, Use either editor.commit(); or  editor.apply();.
                    editor.commit();
                    Intent i = new Intent(SplashActivity.this, StartUpActivity.class);
                    startActivity(i);
                    finish();
                } else {
                        Intent i = new Intent(SplashActivity.this, HomeActivity.class);
                        startActivity(i);
                        finish();
                }
                    }

答案 2 :(得分:2)

如果您不调用commit()或apply(),则不会保存您的更改。

  • Commit()将更改同步并直接写入文件
  • Apply()将更改写入内存中的SharedPreferences 立即但开始异步提交到磁盘

答案 3 :(得分:2)

您可以添加@SuppressLint("CommitPrefEdits")来忽略此消息。就我而言,我正在使用它,因为我想在班级中使用相同的editor字段。

public class ProfileManager {

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    @SuppressLint("CommitPrefEdits")
    @Inject
    ProfileManager(SharedPreferences preferences) {
        this.preferences = preferences;
        this.editor = preferences.edit();
    }

    public void setAccountID(int accountID) {
        editor.putInt(AppConstants.ACCOUNT_ID_KEY, accountID)
                .apply();
    }

    public int getAccountID() {
        return preferences.getInt(AppConstants.ACCOUNT_ID_KEY, AppConstants.INVALID_ACCOUNT_ID);
    }

}