//在一個片段sharedPreferences返回空值
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.
但是它在另一個片段,我需要閱讀的價值,而是返回null。
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
Log.d(TAG, "value: " + preferences.getString("aKeyString",""));
//Logs out "value: null"
爲什麼它爲空?我正在使用getDefaultSharedPreferences
,這將確保我訪問正確的數據,並且出於同樣的原因getActivity().getApplicationContext()
。
對SO有關的喜好返回null類似問題的帖子被建議使用:
'申請();'而不是'commit();'我已經是。 或 他們建議使用'getDefaultSharedPreferences',而不是'getSharedPreferences',我也是。
爲什麼它是空的?
嗨你爲什麼使用apply?爲什麼不提交? – Saveen
@Saveen'apply()'比'commit()'快。 –
不應該'getActivity()。getApplicationContext'是'getActivity()。getApplicationContext()'?錯字? –