android - 无法立即从共享首选项中获取值(value)

标签 android android-fragments android-activity android-sharedpreferences

我将数据存储在共享首选项中

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("menu_bar","abcd");
editor.apply(); 

我正在从 fragment 中的共享首选项中获取数据

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String name = preferences.getString("menu_bar","");
if(!name.equalsIgnoreCase("")){
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();

当应用程序从堆栈中删除时,它正在工作。 但第一次它不起作用。第一次得到 NULL,但第二次工作正常。保存时我还尝试使用 editor.commit()

最佳答案

使用getSharedPreferences("MyPref", Context.MODE_PRIVATE),然后提交立即反射(reflect)更改

SharedPreferences preferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("menu_bar","abcd");
editor.commit(); 

Official Documentation

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Note that when two editors are modifying preferences at the same time, the last one to call apply wins.

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

You don't need to worry about Android component lifecycles and their interaction with apply() writing to disk. The framework makes sure in-flight disk writes from apply() complete before switching states.

The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().

关于android - 无法立即从共享首选项中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150283/

相关文章:

android - 如何实现 onShowCustomView 方法?

android - Webview 闪烁 Android 10 : "tile memory limits exceeded, some content may not draw" Multiple WebViews inside my app

android - fragment 中的 GraphView

java - Android SDK 错误 (BNR)

java - 如何在 Android Studio 中将 Activity 转换为 fragment ?

android - CSS 不适用于 WebView.loadDataWithBaseURL

Android:如何获取所有可用 Intent 过滤器的列表?

android - Action Bar 的 Home 按钮的 onClick 监听器

android - Bug 录制视频 android

java - 正确地保留方向变化的听众