SharedPreferences being reset after force close

☆樱花仙子☆ 提交于 2019-12-18 09:01:11

问题


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();
}

As soon as I kill my app all of my data gets set back to the default settings in my SharedPreferences save method.

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.


Edit: 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!


回答1:


Ok I was able to solve this by removing the "protected static" from my save method.

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.

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.

TIP:

Do not use static methods for getting or setting shared preferences



来源:https://stackoverflow.com/questions/11480871/sharedpreferences-being-reset-after-force-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!