首页 文章

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

提问于
浏览
1

我正在为我的应用程序的Intro Slider使用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 回答

  • 2

    您可以添加 @SuppressLint("CommitPrefEdits") 以忽略此消息 . 在我的情况下,我正在使用它,因为我想在我的 class 中使用相同的 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);
        }
    
    }
    
  • 2

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

    • Commit()将更改同步并直接写入文件

    • Apply()立即将更改写入内存中的SharedPreferences,但开始异步提交到磁盘

  • 4

    Simple Method

    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();
                    }
                        }
    
  • 1

    如果我在调用edit()后没有调用commit()或apply()会发生什么?

    没有 .

相关问题