Rya*_*TCB 3 android sharedpreferences android-fragments
//在一个片段中
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.
Run Code Online (Sandbox Code Playgroud)
但是,在另一个Fragment中,我需要读取该值,但返回null。
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
Log.d(TAG, "value: " + preferences.getString("aKeyString",""));
//Logs out "value: null"
Run Code Online (Sandbox Code Playgroud)
为什么它为空?我正在使用getDefaultSharedPreferences它将确保getActivity().getApplicationContext()出于相同的原因我正在访问正确的数据。
关于SO返回首选项的类似问题的帖子建议使用:
'应用();' 而不是'commit();' 我已经是 或者他们建议使用“ getDefaultSharedPreferences”而不是“ getSharedPreferences”,我也是。
为什么它为空?
您以正确的方式进行操作,但奇怪的是,您指定了默认的空字符串值时,它显示为“ null”,根据javadoc,这应该是不可能的:
/**
* Retrieve a String value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a String.
*
* @throws ClassCastException
*/
@Nullable
String getString(String key, @Nullable String defValue);
Run Code Online (Sandbox Code Playgroud)
您确定它不会在这里引发异常,并且可以解释为什么看不到日志行吗?
我建议你用
布尔commit();
并检查返回值。不幸的是,apply方法将其更改提交到内存中,但启动了对磁盘的异步提交,并且不会收到任何故障通知。