当应用程序被强制关闭或崩溃时,共享首选项会重置 [英] Shared Preferences reset when the app is force closed or crashes

查看:20
本文介绍了当应用程序被强制关闭或崩溃时,共享首选项会重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到如果应用程序被强制关闭或由于某种原因被系统杀死,我的应用程序的 SharedPreferences 将完全重置.显然,是的,我首先应该避免崩溃,但它确实发生了.如果确实发生了这种情况,用户不应丢失其所有设置以及与首选项一起存储的其他数据.

I have noticed that my app's SharedPreferences are completely reset if the app is force closed or is killed by the system for some reason. Obviously, yes, I should avoid having a crash in the first place but it does happen. If it does happen, the user shouldn't loss all of their settings and other data stored with the Preferences.

我在 Google 网上论坛上找到了 这个帖子,但他们不能解决不了.

I found this thread on Google Groups but they couldn't solve it.

任何人都知道为什么或如何发生这种情况以及是否有办法防止它?

Anyone have any insight into why or how this happens and if there is a way to prevent it?

另外,我在 2.1 和 2.2 设备上看到过这个.每次崩溃都会发生这种情况,而不仅仅是其中一些.

Also, fyi I have seen this on a 2.1 and a 2.2 device. It will happen on every crash, not just some of them.

谢谢

推荐答案

经过一番挖掘,我终于找到了问题的根源.由于我的代码中的错误,字符串首选项被保存为空键.因此,在加载首选项时崩溃后,首选项 xml 文件中有一个空白,导致首选项崩溃并被重置.出于某种原因,我没有得到首选项崩溃的堆栈跟踪,只有初始崩溃的直接原因.

After some digging around I finally discovered the source of the problem. Through an error in my code, a string preference was getting saved with a null key. So after the crash when it went to load the Preferences there was a blank in the preferences xml file which caused the preferences to crash and be reset. For some reason I was not getting the stack trace of the preference crash, only the immediate cause of the initial crash.

只是添加更多细节以防其他人将来遇到类似问题:

Just to add some more details in case someone else has a similar problem in the future:

在强制关闭按钮按下之前,具有首选项的 xml 文件保持不变.然而,下次访问共享首选项时,xml 文件被清除并重新启动.

The xml file that has the preferences stayed intact up to and through the force close button press. The next time the shared preferences were accessed however, the xml file was cleared and started anew.

这篇关于当应用程序被强制关闭或崩溃时,共享首选项会重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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