SharedPreferences being reset after force close(SharedPreferences 在强制关闭后被重置)
问题描述
我已经能够在我的应用程序中成功实现共享首选项,但是如果我通过任务管理器终止应用程序,我会遇到数据被重置/删除的问题.
I have been able to successfully implement Shared Preferences into my application but I have ran into a problem with the data being reset/deleted if I kill the application through a task manager.
我正在使用静态方法进行保存,这样我只需要该方法一次,并且可以在我的应用程序中的任何地方调用它.
I am using a static method for saving, that way I only need the method once and can call it everywhere within my app.
protected static synchronized void save(Context cntx){
SharedPreferences preferences2 = cntx.getSharedPreferences("BluRealms", 0);
SharedPreferences.Editor editor = preferences2.edit();
editor.putBoolean("level", Stats.level);
editor.commit();
}
一旦我终止我的应用程序,我的所有数据都会在我的 SharedPreferences 保存方法中恢复为默认设置.
As soon as I kill my app all of my data gets set back to the default settings in my SharedPreferences save method.
我也做了一些搜索,发现一些帖子说在清单文件中添加 android:persistent="true" 可以解决问题,但即使这样,数据仍然会重置.
I also did some searching and found a few posts that say adding android:persistent="true" into the of the manifest file would fix the problem, yet the data is still reset even with this.
好吧,我想我找到了一些关于我的问题的信息.此问题突出了三星 Galaxy S 手机无法正确保存 SharedPreferences 的问题,这是我正在测试的设备.http://code.google.com/p/android/issues/detail?id=14359 - 特别是comment 6
Well I think I found a bit of information on my problem. This Issue highlights a problem with Samsung Galaxy S phones not saving SharedPreferences properly, which is the device I am testing on. http://code.google.com/p/android/issues/detail?id=14359 - especially comment 6
如果有更多关于这方面的信息会很棒!
Any more information on this would be great!
推荐答案
好的,我能够通过从我的保存方法中删除受保护的静态"来解决这个问题.
Ok I was able to solve this by removing the "protected static" from my save method.
我没有调用全局保存方法,而是简单地将保存方法放在需要保存的每个类中,然后只在 onPause() 和 onDestroy() 方法中调用保存方法.
Instead of calling a global save method, I simply placed the save method in each class that would need to save and then only call the save method in the onPause() and onDestroy() methods.
我注意到,如果我在一个类中调用 save() 次数过多,当我关闭应用程序时,它似乎也会删除我的 SharedPreferences.
I noticed that if I called save() too many times within a class that also seemed to erase my SharedPreferences when I closed the app.
提示:
不要使用静态方法来获取或设置共享首选项
Do not use static methods for getting or setting shared preferences
这篇关于SharedPreferences 在强制关闭后被重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SharedPreferences 在强制关闭后被重置
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01