gpt4 book ai didi

android - 没有立即从共享首选项中获得值(value)

转载 作者:行者123 更新时间:2023-11-30 00:32:01 26 4
gpt4 key购买 nike

我将数据存储在 Shared Preferences 中

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) 然后 commit 立即反射(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com