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.

36 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
    Replies
    1. IEEE Project Domain management in software engineering is distinct from traditional project deveopment in that software projects have a unique lifecycle process that requires multiple rounds of testing, updating, and faculty feedback. A IEEE Domain project Final Year Projects for CSE system development life cycle is essentially a phased project model that defines the organizational constraints of a large-scale systems project. The methods used in a IEEE DOmain Project systems development life cycle strategy Project Centers in Chennai For CSE provide clearly defined phases of work to plan, design, test, deploy, and maintain information systems.


      This is enough for me. I want to write software that anyone can use, and virtually everyone who has an internet connected device with a screen can use apps written in JavaScript. JavaScript Training in Chennai JavaScript was used for little more than mouse hover animations and little calculations to make static websites feel more interactive. Let’s assume 90% of all websites using JavaScript use it in a trivial way. That still leaves 150 million substantial JavaScript Training in Chennai JavaScript applications.

      Delete
  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
  9. I have read your blog its very attractive and impressive. I like it your blog.

    Abinitio Online Training
    Hadoop Online Training
    Cognos Online Training

    ReplyDelete
  10. I have a question.
    I am trying to use your code to save a list in shared preferences, since I am adding the items on btn click. I am able to store the data and then use it, but when I close the app, I can't get the data back and use it again.
    Any help will be greatly appreciated.
    Thanks.

    ReplyDelete
  11. Download latest audio and video file fromvidmate

    ReplyDelete
  12. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me..
    Android Online Training

    ReplyDelete

  13. Body pain is a very common issue that we have to face in our daily life. When you face the issue of pain, it is best if you take the help of the doctor. But every time, you cannot get the help of the doctor. In those situations, to get quick and effective relief from pain, you take the help of the painkillers. Soma pill is an effective painkiller by using which you can get instant relief from your pain. This painkiller has Carisoprodol as the active ingredient. You can buy Soma 350 easily from the market. To enjoy the effects of this painkiller at an affordable price, buy Soma 350 mg online.
    Buy Soma online

    ReplyDelete