Skip to content
Advertisement

SharedPreferences being reset after force close

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!

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement