String arrays and Object arrays in SharedPreferences

I see many questions on SO asking about the best mechanism to store some kind of preferences such as statistics, favorites, or shortcuts. Many of these questions are answered with "Use a database".

The biggest, yet clear, secret is that SharedPreferences are actually implemented using a
database. To check it, add some SharedPreferences to your app (Get the Editor and commit some changes). Now, run the app on the emulator, and got to DDMS and check the files of your package: you will see the database there. Okay, I take that back! It is an XML file. I saw it once from a long time and it seems I thought back then that it was a database and the idea just stuck in my small brain! However everything still applies, as we all know, we can export a database into an excel sheet so no problem concept-wise.

 Anyway, SharedPreferences according to the android documentation
is a class that provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.
Now let us take an example and try to mirror a database onto SharedPreferences.

Say, we have a utility app that allows you to surf the net, and one of the features is to add bookmarks. Technically, the user has an array of Urls which are the bookmarks.
On the first occasion, it would seem inconvenient to use Shared Preferences to save this array. However, it turns out that doing so is rather simple and to a very great extent has the same complexity of using a database.

An array representation boils down to an integer representing a size and
You could simply add a function setBookmarks that saves this array.
Not to lose generality I will show a function that will actually save an array and I will call it saveArray.


public boolean saveArray(String[] array, String arrayName, Context mContext) { 
  SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
  SharedPreferences.Editor editor = prefs.edit();
  editor.putInt(arrayName +"_size", array.length);
  for(int i=0;i<array.length;i++)
    editor.putString(arrayName + "_" + i, array[i]);
  return editor.commit();
}

Now to get the array back, we just do the reverse operation and lets call it loadArray


public String[] loadArray(String arrayName, Context mContext) {
  SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
  int size = prefs.getInt(arrayName + "_size", 0);
  String array[] = new String[size];
  for(int i=0;i<size;i++)
    array[i] = prefs.getString(arrayName + "_" + i, null);
  return array;
}

This whole implementation could actually be used to save a bit more complex classes.
Say that your Bookmark entity has an integer representing maybe the number of views.
The same approach can be made to save the whole data of the ith object.

a sort of serialization.

14 comments:

  1. "SharedPreferences are actually implemented using a database" -- no, they are "actually implemented" using an XML file.

    ReplyDelete
    Replies
    1. OOPS! you are right! I just rechecked. It seems I saw it once a long time and for some reason I thought it was a db. Anyway, everything still applies.

      Delete
  2. Thank you Very much for the simple and straight forward solution .....

    ReplyDelete
  3. Thanks very much for the explanation!

    ReplyDelete
  4. The problem with this approach is that you'll pollute your preferences. Say, you save an array with 100 entries and then shrink it ito 2. You'll still have 100 entries in your preferences unless you clean it up first.

    ReplyDelete
    Replies
    1. Exactly you should clean up first before saving the array ( I will edit it when I have time )

      Delete
  5. Hello and thanks for your post! A question: is a good way use this code for save 800 entries?

    :-)

    Pol

    ReplyDelete
    Replies
    1. I think the performance will be the same as the database if you tweak the data loading a bit.

      Delete
  6. Good work.............also get a detail tutorial with sample project at......http://androidtutorialsrkt.blogspot.in/

    ReplyDelete
  7. Everyone wants to get unique place in the IT industry’s for that you need to upgrade your skills, your blog helps me improvise my skill set to get good career, keep sharing your thoughts with us.

    Android Online Training

    ReplyDelete
  8. Excellent blog has been shared by you. Its very interesting and useful to me and my friends too...! keep update such kind of interesting post. thank you for share this blog to us. Android Training in Chennai | Salesforce Training in Chennai

    ReplyDelete