SharedPreferences is reset after forced shutdown
I’ve been able to successfully implement shared preferences in my app, but if I terminate the app via Task Manager, I’m having issues resetting/deleting data.
I’m saving with a static method so that I only need the method once and can call it anywhere in my application.
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();
}
Once I terminate my application, all my data reverts to the default settings in my SharedPreferences save method.
I also did some searching and found some posts saying that adding android:persistent=”true” to the list file fixes the problem, but even then the data is reset.
EDIT: Well, I think I found some information about my question. This issue highlights the issue of Samsung Galaxy S phones not saving SharedPreferences correctly, which is the device I am testing. http://code.google.com/p/android/issues/detail?id=14359 – especially Comment 6
It would be nice to have more relevant information!
Solution
Ok, I was able to fix this by removing “protected static” from my save method.
Instead of calling the global save method, I put the save method in every class that needs to be saved, and then only call the save method in the onPause() and onDestroy() methods.
I’ve noticed that if I call save() too many times in a class, it seems to remove my SharedPreferences when I close the app.
Hint:
Do not use static methods for getting or setting shared preferences