【问题标题】:SharedPreferences does not store valueSharedPreferences 不存储值
【发布时间】:2016-05-21 13:44:46
【问题描述】:

我目前正在使用 Android 中的 SharedPreferences,但遇到了我无法解释的奇怪行为。这是我的代码:

SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
appPreferences.edit().putBoolean("launched_before", true);
appPreferences.edit().apply();
appPreferences = null;
appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean test = appPreferences.getBoolean("launched_before", false); //this is false

我写入 SharedPreferences 的值没有被保存。我知道我可以使用getDefaultSharedPreferences(),但我不想在这里这样做,因为默认文件存储其他值。

当我使用commit()而不是apply()时,commit()的返回值为true,但我仍然无法正确加载文件。

【问题讨论】:

  • 我相信应用 SharedPreferences 是一个异步操作,因此不能保证同步代码中的结果。放入布尔值后,您是否尝试过获取布尔值?我看不出重新分配的意义
  • @cricket_007 无论我在哪里尝试阅读,它都是错误的

标签: android sharedpreferences


【解决方案1】:

发生这种情况是因为您的代码没有按照您的想法执行。当您调用 edit() 时,它不会启动“编辑事务”。相反,每次调用它时它都会返回一个新的 Editor 对象实例。那么让我们看看这段代码:

SharedPreferences appPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE);

// Here you create a FIRST Editor object, which stores the modification
// You never call apply() on this object, and thus your changes are dropped.
appPreferences.edit().putBoolean("launched_before", true);

// Here you create a SECOND Editor object (which has no modifications)
// and you call apply() on it, thus changing nothing.
appPreferences.edit().apply();

您创建了第一个编辑器对象并将设置放入其中,但您在 second 编辑器对象上调用了应用,该编辑器对象没有任何更改。由于您从未在已修改的编辑器对象上调用 apply(),因此您的更改从未保存。

修复很明显 - 使用单个 Editor 实例进行修改,并在此实例上调用 apply/commit:

SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = appPreferences.edit();
ed.putBoolean("launched_before", true);
ed.apply();

【讨论】:

    【解决方案2】:

    在这里,您可以将“com.yourdomain.yourapp.your_key_name”用作键,并为每个值使用另一个键...试试这个

    private SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
    
    public void putBoolean(String key, boolean value) {
        checkForNullKey(key);
        preferences.edit().putBoolean(key, value).apply();
    }
    
    public boolean getBoolean(String key) {
        return preferences.getBoolean(key, false);
    }
    
    public void checkForNullKey(String key){
        if (key == null){
            throw new NullPointerException();
        }
    }
    

    【讨论】:

    • 这与我的问题有什么关系?我不想使用 defaultSharedPreferences
    • 因为它不会覆盖您的默认存储值?如果我明白你需要什么?每次使用 putBoolean("com.blabla.someapp.testBoolean1", true) 和 putBoolean("..... .testBoolean2, false) 时,它都会为 testBoolean1 存储 true 并为 testBoolean2 存储 false ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多