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.

56 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. very nicely explained....Thanks !!

    ReplyDelete
  8. 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
  9. 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
  10. 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
  11. 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
  12. Download latest audio and video file fromvidmate

    ReplyDelete
  13. 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

  14. 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
  15. Love to read this page. Watch all the pinoy swertres results daily.
    Swertres Lotto result Today
    pinoyswertres

    ReplyDelete
  16. ftv is a Porn Training site. ftv is the largest Amateur porn training institute with the hottest selection Online and offline real life cam.
    bangla sex video

    ReplyDelete
  17. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    Online Training, Online Training Institute, Online Course, Online Training Courses

    ReplyDelete

  18. Top Real Estate Agent in Toronto
    Best Real Estate Realtor in Brampton
    Realtor Piyush is a one of the best real estate realtor in brampton. We have more than 10+ years of experience in this field. We are specializes in buying, selling, leasing and investing in properties of Brampton. We also cover wide area of field Mississauga and around many places.

    ReplyDelete
  19. Top mortgage broker in Brampton
    Best mortgage broker Toronto
    We work with Canada's premium financial institutions to offer you the best mortgages in the market and the lowest interest rates. Names such as Royal Bank, Scotia Bank, Bank of Montreal, TD Canada Trust, CIBC, National Bank, and more, guarantee the best service and highest savings for you.

    ReplyDelete
  20. Top mortgage broker in Brampton
    Best mortgage broker Toronto
    We work with Canada's premium financial institutions to offer you the best mortgages in the market and the lowest interest rates. Names such as Royal Bank, Scotia Bank, Bank of Montreal, TD Canada Trust, CIBC, National Bank, and more, guarantee the best service and highest savings for you.

    ReplyDelete
  21. Top mortgage broker in Brampton
    Best mortgage broker Toronto
    We work with Canada's premium financial institutions to offer you the best mortgages in the market and the lowest interest rates. Names such as Royal Bank, Scotia Bank, Bank of Montreal, TD Canada Trust, CIBC, National Bank, and more, guarantee the best service and highest savings for you.

    ReplyDelete
  22. Best realtor in Brampton
    Best Real estate agent in Toronto
    Realtor Piyush is a one of the best real estate realtor in brampton. We have more than 10+ years of experience in this field. We are specializes in buying, selling, leasing and investing in properties of Brampton. We also cover wide area of field Mississauga and around many places.

    ReplyDelete
  23. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    workday studio online training
    best workday studio online training
    top workday studio online training

    ReplyDelete
  24. Thanks for the informative article About Android. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete

  25. I am very happy when read this blog post because blog post written in good manner and write on good topic. Thanks for sharing valuable information.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete

  26. I am very happy when read this blog post because blog post written in good manner and write on good topic. Java training in chennai Thanks for sharing valuable information.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  27. Thanks for sharing a worthy information. This is really helpful. Keep doing more.

    LEGO Toys

    ReplyDelete
  28. Pretty Post! It is really interesting to read from the beginning & I would like to share your blog to my circles for getting awesome knowledge, keep your blog as updated. Software Testing Training in Chennai | Software Testing Training in Anna Nagar | Software Testing Training in OMR | Software Testing Training in Porur | Software Testing Training in Tambaram | Software Testing Training in Velachery

    ReplyDelete