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

标签 android

我正在尝试使用两个不同的 sharepreferences 实例读取 sharedpreference 中字段的值。虽然使用第一个实例读取给出了正确的结果,但使用第二个实例的第二个读取操作返回了默认值。为什么会这样?我在这里是否遗漏了一些重要的概念?

代码:

  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.

我的案例是否与这句话中的概念有关?

最佳答案

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

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

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

关于android - Sharedpreference 的多个实例为同一字段提供不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433423/

相关文章:

Android生命周期哪个事件在生命周期内只触发一次?

android - 如何从第二个 Activity 返回导航后不缓冲地播放视频?

java - 从 Android 更新 Facebook

android - 自定义 Google Plus 登录按钮和 Facebook 登录按钮

java - Android 使用 Volley 从网络服务器下载文件

android - 将消息从一个 Activity 发送到另一个 Activity

java - 如何从MySQL数据库获取数据到android

android - 在不创建帐户的情况下使用 SyncAdapter

java - 在 MotionEvent.ACTION_MOVE 上重绘 View

android - 在 Android 中设置和取消设置默认应用