Monday, July 12, 2010

Android SharedPreference Read-Once Gotcha

I use SharedPreferences in a horrible way.  I use it to store application data. It's much easier to use a key/value store than a SQLite DB or writing to a file.  

Because SharedPreferences are stored in the /data/data directory they can't be reached without root for saving.  To fix this I store a copy of the file on the /sdcard.  On start up I copy the "public" version over the /data/data private file.  (This has the side effect of allowing modification of the data and reloading by editing the file when attached to a computer)

The problem is that when you call getSharedPreferences you always get the same instance back. It doesn't reload the file.  This was an issue for me because I was using that to create the /data/data file if it didn't exist, copy the /sdcard file over and then tried to reload by calling it again.  

To fix the problem I had to check if the /data/data file existed during the copy operation and create through java.io.File methods first, then copy, then call getSharedPreferences.

No comments: