SharedPreferences不存储值

时间:2016-05-21 13:44:47

标签: android sharedpreferences

我目前正在使用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,但我仍然无法正确加载文件。

3 个答案:

答案 0 :(得分: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();

您创建了放置设置的第一个编辑器对象,但是在没有更改的第二个编辑器对象上调用了apply。由于您从未在已修改的编辑器对象上调用apply(),因此您的更改从未保存。

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

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

答案 1 :(得分:0)

SharedPreferences appPreferences = contect.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appPreferences.edit();
editor.putBoolean("launched_before", true);
editor.commit();
appPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean test = appPreferences.getBoolean("launched_before", false);

尝试这个,这应该像冠军一样。

答案 2 :(得分:0)

在这里你可以使用键“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();
    }
}