SharedPreferences are sometimes deleted
My app uses SharedPreferences (with the help of a PreferenceActivity) to store all settings. But sometimes all settings are deleted and all values are set back to d开发者_运维技巧efault. Mostly on Android 3.x tabs. On normal smartphones there are no problems.
I have observed that all settings are deleted when the application process is killed by Android. I noticed this because the notification icon is no longer displayed. I also wonder why the process is killed on tablets and not on smartphones. On my smartphone the notification icon never disappears.
My app also has a service, the main process and the service both read and write settings to the SharedPreferences. I've sometimes noticed that all settings are cleared once the service writes to the SharedPreferences. But it does not happen every time.
Any ideas? I realize that the SharedPreferences should not be used by different processes, but it works on all smartphones without problems!
I found out the reason why the settings disappear: If two processes write data to SharedPreferences, it can happen that all SharedPreferences are reset to default values. In my case all settings are cleared when the service write the first data to SharedPreferences.
Now, the service provides only read access to the SharedPreferences. The settings that are accessed by both processes writing are stored in a database.
SharedPreferences usually work great and as you mentioned without any problem on smartphones. It should also work on tablets. However it would be best to use sqlite or backing your shared prefs on a server for each users id data loss is a problem.
I have had the same issue.
All values from shared preferences become default if one value occasionally written with key = null
. This is possible when you creating new constants using Eclipse, which inits them with null by default, and then you forgot to go to the beginning of the class and change constant to some meaningful value.
If you continue using the app, read operation of shared preferences will return valid values.
But when context is changed(for example, when activity killed by android and recreated) all values from shared preferences will return default values(zeroes).
So check your shared preferences's keys! I hope this answer will help someone.
精彩评论