Sharedpreference的多个实例为同一字段提供不同的值

时间:2014-08-21 18:25:27

标签: android

我正在尝试使用两个不同的sharepreferences实例来读取共享首选项中字段的值。虽然使用第一个实例读取正在给出正确的结果,但使用第二个实例的第二个读取操作返回默认值。为什么会这样?我在这里错过了一些重要的概念吗?

代码:

  public void testMethod(){

    SharedPreferences pref1=myContext.getSharedPreferences(PreferenceHelper.MY_PREF, myContext.MODE_PRIVATE);
    //Correct value is obtained here...
    String value1=pref1.getString("KEY", "");

    SharedPreferences pref2=myContext.getSharedPreferences(PreferenceHelper.MY_PREF, myContext.MODE_PRIVATE);
    //Incorrect value is obtained here...
    String value2=pref2.getString("KEY", "");

}

我怀疑这是由于同一偏好的多个实例.Android文档声明:

 Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

我的案子与这句话中的概念有关吗?

1 个答案:

答案 0 :(得分:3)

由于你调用commit()而不是apply(),其中一个没有保存,你得到了错误的答案。查看文档:

与commit()同步地将其首选项写入持久存储,apply()会立即将其更改提交到内存中的SharedPreferences,但会启动异步提交到磁盘,并且不会通知您任何失败。如果此SharedPreferences上的另一个编辑器在apply()尚未完成时执行常规commit(),则commit()将阻塞,直到完成所有异步提交以及提交本身。

以上来自http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()