共享preferences不节能值正常 [英] SharedPreferences not saving values properly

查看:173
本文介绍了共享preferences不节能值正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个字符串保存到共享preferences。我试图做到这一点的方法如下:

I'm trying to save a string to the shared preferences. The way I've tried to do this is the following:

ISharedPreferences _prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor _editor = _prefs.Edit();
_editor.PutString("myString", "123");
_editor.Commit();

再往下我试着打印出我的字符串:

Further down i try to print out my string:

_txtView.Text = _prefs.GetString("myString", "Can't find string");

当我运行应用程序TextView的我现在正确打印出123。所以,一切工作按预期。然而;共享preferences的一点是,它的持久性。所以,如果我现在尝试注释掉以下两行:

When I run the application my textview now properly prints out "123". So everything is working as intended. However; the point of sharedpreferences is that it's persistent. So if I now try to comment out the following two lines:

_editor.PutString("myString", "123");
_editor.Commit();

然后建立再次,我的TextView显示无法找到字符串。因此,出于某种原因,该字符串没有被保存?有谁看到这是为什么?

Then build again, my textview displays "can't find string". So for some reason the string isn't being saved? Does anyone see why this is?

谢谢!

推荐答案

但是,共享的preferences的一点是,它的持久的:这是应用执行之间持续。当你注释掉code和发射再次要创建一个的新鲜的应用程序,没有默认值存储preferences。这就是为什么当你把它注释掉不工作。

However, the point of sharedpreferences is that it's persistent : It is persistent between app executions. When you comment out the code and launch again you are creating a fresh app, with no default stored preferences. That is why it is not working when you comment it out.

如果你想让它在共享preferences存储只有一次,那么你应该做一个检查是否正在为执行应用程序的的首次的或没有,那么如果的真正的,存储在共享preferences。

if you want it to store in shared preferences only once, then you should do a check whether the app is being executed for the first time or not, and then if true, store in shared preferences.

这篇关于共享preferences不节能值正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆