【发布时间】:2016-06-18 01:16:29
【问题描述】:
//在一个片段中
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("aKeyString", "aValueString");
editor.apply()
//If I try to log the just saved value the log is empty. Though I thought the apply(); committed that value to memory instantly and later to disc. So should be readable ?
Log.d(TAG, preferences.getString("aKeyString",""));
//nothing is logged to logcat at all. Not even a blank line.
但是,我需要在另一个 Fragment 中读取该值但返回 null。
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
Log.d(TAG, "value: " + preferences.getString("aKeyString",""));
//Logs out "value: null"
为什么它是空的?我正在使用getDefaultSharedPreferences,这将确保我访问正确的数据和getActivity().getApplicationContext(),原因相同。
关于 SO 有关返回 null 的首选项的类似问题的帖子建议使用:
'应用();'而不是“提交();”我已经是了。 要么 他们建议使用 'getDefaultSharedPreferences' 而不是 'getSharedPreferences' 我也是。
为什么它是空的?
【问题讨论】:
-
@Saveen
apply()比commit()快。 -
getActivity() 可能为 null 有检查吗?
-
commit 会阻止 UI,同时它会立即保存并应用保存到内存,以便可以使用然后异步到磁盘。
-
好的,谢谢@RyanTCB 和 Bob Malooga
-
@BobMalooga 是的,错字已更正,谢谢
标签: android android-fragments sharedpreferences