Android SharedPreferences 值未更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10186215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SharedPreferences value is not updated
提问by Juned
I am trying to update the values of SharedPreferences, here is my code:
我正在尝试更新SharedPreferences的值,这是我的代码:
edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putString(Settings.PREF_USERNAME+"",txtuser);
edit.putString(Settings.PREF_PASSWORD+"",txtpass);
edit.commit();"
The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.
问题是当我访问这个值时,它没有返回更新的值,它给了我一个 SharedPreferences 的值。
But when I am confirming the data in XMLfile ,the data updated in that.
但是当我确认XML文件中的数据时,数据更新了。
And after restarting my application I am getting that updated values. So it requires me to restart the application to get updated values.
So, how to get those updated values once it changes?
重新启动我的应用程序后,我得到了更新的值。所以它需要我重新启动应用程序以获取更新的值。
那么,一旦发生变化,如何获取这些更新的值呢?
Thanks in advance
提前致谢
Here is my whole code:
这是我的整个代码:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
ctx=this;
status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// get old value
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
on(ctx,true);// function will call and value is updated
}
}});
status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// this should give me a updated value but gives old value
}
public static boolean on(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Settings.PREF_ON, Settings.DEFAULT_ON);
}
public static void on(Context context,boolean on) {
if (on) Receiver.engine(context).isRegistered(); //
}
**********in reciver file***********
public void isRegistered ) {
Editor edit = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).edit();
edit.putString(Settings.PREF_STATUS+"","0");
edit.commit();
}
回答by waqaslam
Instead of using edit.commit();
, you should use edit.apply();
. Applywill update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.
而不是使用edit.commit();
,你应该使用edit.apply();
。Apply将立即更新首选项对象并将异步保存新值,因此允许您读取最新值。
commit()
犯罪()
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 commit wins.
If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.
将此编辑器的首选项更改提交回它正在编辑的 SharedPreferences 对象。这会自动执行请求的修改,替换当前 SharedPreferences 中的任何内容。
请注意,当两个编辑器同时修改首选项时,最后一个调用 commit 的人获胜。
如果您不关心返回值并且正在从应用程序的主线程使用它,请考虑改用 apply()。
apply()
申请()
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.
将此编辑器的首选项更改提交回它正在编辑的 SharedPreferences 对象。这会自动执行请求的修改,替换当前 SharedPreferences 中的任何内容。
请注意,当两个编辑器同时修改首选项时,最后一个调用 apply 的人获胜。
与将其首选项同步写入持久存储的 commit() 不同,apply() 立即将其更改提交到内存中的 SharedPreferences,但会启动对磁盘的异步提交,并且您不会收到任何失败通知。如果此 SharedPreferences 上的另一个编辑器在 apply() 仍然未完成时执行常规 commit(),则 commit() 将阻塞,直到完成所有异步提交以及提交本身。
由于 SharedPreferences 实例是进程中的单例,如果您已经忽略了返回值,则将 commit() 的任何实例替换为 apply() 都是安全的。
您无需担心 Android 组件生命周期及其与 apply() 写入磁盘的交互。该框架确保在切换状态之前完成来自 apply() 的动态磁盘写入。
回答by Peter
Well, even if my answer came 3 years after the question, I hope it will help. The problem don't seem to came from commit or apply but from the code structure.
好吧,即使我的答案是在问题发生 3 年后才出现的,我希望它会有所帮助。问题似乎不是来自 commit 或 apply 而是来自代码结构。
Let's explain: on a smartphone, you run an APP but you don't quit the APP as we do on computers. This mean when you come back to the menu of the smartphone, the APP is still "running". When you "click" again on the APP icon, you don't re-run the APP but just awake it. In juned code, we can see he calls getDefaultSharedPreferences inside his Create function.
让我们解释一下:在智能手机上,您运行一个APP,但您不会像我们在电脑上那样退出该APP。这意味着当您返回智能手机的菜单时,该 APP 仍在“运行”。当您再次“单击”APP 图标时,您不会重新运行该APP,而是将其唤醒。在 juned 代码中,我们可以看到他在他的 Create 函数中调用了 getDefaultSharedPreferences。
So he calls getDefaultSharedPreferences when he runs first time the APP. But when he sets the APP on background and then awakes the APP, the call is not done.
所以他在第一次运行APP时调用了getDefaultSharedPreferences。但是当他将APP设置在后台然后唤醒APP时,呼叫没有完成。
I've had the same problem: I check if I have SharedPreference for my APP. If not, I prompt a form to ask value to the user. If yes, I check the date of the preferences. If too old, I prompt the form. After the form, I save the preferences with the current date. What I noticed is that the test about the existence of the SharedPreference (which was set at the same location than the one of juned) was done only at first run of the APP but not when I awake the APP. This mean that I was unable to check the time limite of my SharedPreferences!
我遇到了同样的问题:我检查我的 APP 是否有 SharedPreference。如果没有,我会提示一个表单向用户询问价值。如果是,我会检查偏好的日期。如果太旧,我会提示表格。在表单之后,我保存了当前日期的首选项。我注意到的是,关于 SharedPreference 是否存在的测试(设置在与 juned 相同的位置)仅在第一次运行 APP 时完成,但在我唤醒 APP 时没有完成。这意味着我无法检查我的 SharedPreferences 的时间限制!
How to solve that? Just add:
如何解决?只需添加:
@Override
public void onResume(){
super.onResume();
// And put the SharedPreferences test here
}
This code will be called at first run of the APP but also each time the user awake it.
此代码将在应用程序第一次运行时调用,每次用户唤醒它时都会调用。
回答by Nitesh Khosla
hope it will help you..
希望它会帮助你..
SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEditr = mypref.edit();
prefsEditr.putString("Userid", UserId);
prefsEditr.commit();
String task1 = mypref.getString("Userid", "");
回答by Shankar Agarwal
Try this code:
试试这个代码:
SharedPreferences edit = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = edit.edit();
editor.putString(Settings.PREF_USERNAME + "", txtuser);
editor.putString(Settings.PREF_PASSWORD + "", entered_name);
editor.commit();
回答by wolverine
Try like this,
试试这样,
public SharedPreferences prefs;
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Settings.PREF_USERNAME+"", txtuser);
editor.putString(Settings.PREF_PASSWORD+"", entered_name);
editor.commit();