Shared Preferences reset when the app is force clo

2019-01-20 08:12发布

问题:

I have noticed that my app's SharedPreferences are completely reset if the app is force closed or is killed by the system for some reason. Obviously, yes, I should avoid having a crash in the first place but it does happen. If it does happen, the user shouldn't loss all of their settings and other data stored with the Preferences.

I found this thread on Google Groups but they couldn't solve it.

Anyone have any insight into why or how this happens and if there is a way to prevent it?

Also, fyi I have seen this on a 2.1 and a 2.2 device. It will happen on every crash, not just some of them.

Thanks

回答1:

After some digging around I finally discovered the source of the problem. Through an error in my code, a string preference was getting saved with a null key. So after the crash when it went to load the Preferences there was a blank in the preferences xml file which caused the preferences to crash and be reset. For some reason I was not getting the stack trace of the preference crash, only the immediate cause of the initial crash.

Just to add some more details in case someone else has a similar problem in the future:

The xml file that has the preferences stayed intact up to and through the force close button press. The next time the shared preferences were accessed however, the xml file was cleared and started anew.