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
相关文章