本文介绍了SharedPreferences.edit() 没有相应的 commit() 或 apply() 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 SharedPreferences 用于我的应用程序的 Intro Slider.但是,我在这一行遇到错误:

class PrefManager {私有 SharedPreferences 首选项;私有 SharedPreferences.Editor 编辑器;private static final String PREF_NAME = "welcome";private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";PrefManager(上下文上下文){int PRIVATE_MODE = 0;pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);编辑器 = pref.edit();}void setFirstTimeLaunch(boolean isFirstTime) {editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);editor.commit();}布尔 isFirstTimeLaunch() {返回 pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);}}

editor = pref.edit();

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

解决方案

如果您不调用 commit() 或 apply(),您的更改将不会被保存.

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

I'm using SharedPreferences for my apps' Intro Slider. However, I'm getting an error on this line:

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);
    }

}

What happens if I don't call commit() or apply() after calling edit()?

解决方案

If you do not call commit() or apply(), your changes will not be saved.

  • Commit() writes the changes synchronously and directly to the file
  • Apply() writes the changes to the in-memory SharedPreferencesimmediately but begins an asynchronous commit to disk

这篇关于SharedPreferences.edit() 没有相应的 commit() 或 apply() 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:31