我正在尝试使用两个不同的 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", "");
}
Run Code Online (Sandbox Code Playgroud)
我怀疑这是由于相同首选项的多个实例所致。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.
Run Code Online (Sandbox Code Playgroud)
我的情况与这句话中的概念有关吗?
由于您调用的是 commit() 而不是 apply(),因此其中之一没有保存并且您得到了错误的答案。查看文档:
与将其首选项同步写入持久存储的 commit() 不同,apply() 立即将其更改提交到内存中的 SharedPreferences,但会启动对磁盘的异步提交,并且您不会收到任何失败通知。如果此 SharedPreferences 上的另一个编辑器在 apply() 仍然未完成时执行常规 commit(),则 commit() 将阻塞,直到完成所有异步提交以及提交本身。
以上来自http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
| 归档时间: |
|
| 查看次数: |
1459 次 |
| 最近记录: |