Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

sharedpreferences - Android - Shared Preferences are lost sometimes

Some of the users of my application complain that sometimes (in a random way) the settings of my application are getting reverted to their default state (usually after a reboot of the phone). I never managed to reproduce the problem though. I am thinking it is due to the fact that in many places in my app I have a piece of code that calls the shared preferences editor and commits changes - Can it resolves in corrupting the shared preference file if I try to commit several changes to the same preference file at the same time? (Multi-thread application)

I am really lost. I tried to look in the web for hours to find a solution without a success.

If anyone has even an idea so I can start investigating, I would be grateful.

Thanks, Amit Moran

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I'd echo the other answers - that you need to avoid conflicts if you don't want to corrupt the file - and I'd go further to suggest that you're probably misuing SharedPreferences.

SPs are designed to store small pieces of information about your app - user settings like volume or whether music is playing or things like that.

SPs are NOT designed for storing data which changes often and/or large amounts of data and it's a bad idea to try to do this (for the reasons you've discovered and a few others).

Remember that SPs are really just an XML file - you're incurring the overhead of parsing and recreating that every time you change it too!

The idea of an App which updates SPs in more than one thread is a bit mad I think - you need a better way of managing and storing the data you're saving - it will pay-off for you in more than one way...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...