Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...