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.

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

    ReplyDelete
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. Thanks for sharing a worthy information. This is really helpful. Keep doing more.

    LEGO Toys

    ReplyDelete
  21. 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
  22. Find live NFL scores, pro football player & team news, NFL videos, rumors, stats, standings, team schedules & fantasy football games on FOX Sports.
    Watch 49ers Live
    Watch Eagles Live
    Watch Bills Live
    Watch Chargers Live
    Watch Titans Live

    ReplyDelete
  23. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Python Online Training

    ReplyDelete
  24. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Azure Online Training

    ReplyDelete
  25. Thanks for a marvelous posting! I truly enjoyed reading it, yyou
    might be a great author. I will make sure to bookmark your blog and will come back very soon. 바카라사이트

    ReplyDelete
  26. I want to encourage you conttinue
    your great writing, have a nice day! 온라인경마

    ReplyDelete



  27. Nice post. I used to be checking constantly this blog and I am impressed! Extremely useful info particularly the ultimate section 🙂 I take care of such information a lot. I was seeking this certain information for a long time. Thank you and best of luck.
    what are the advantages and disadvantages of online classes, BOOKS PDF DOWNLOAD

    ReplyDelete
  28. Finish the Selenium Training in Chennai from Infycle Technologies, the best software training institute in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Java, Hadoop, Big Data, Android, and iOS Development, Oracle, etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

    ReplyDelete
  29. A Windows 7 Professional product key is required to verify a copy of the Windows 7 professional. The product key is a 25-character digit code.Windows 7 Product Key Crack

    ReplyDelete
  30. pg auto เครดิต ฟรี แจกจริงกดรับ เครดิต ฟรี pg slot ได้ด้วยตัวเอง ชื่นชอบคิดโปรโมชั่นดีๆมาเพื่อลูกค้าที่น่ารักน่าชังของเราเสมอ แต่บทนี้เราจะมากมายล่าวถึงประเด็นการแจกเครดิตฟรีแบบไม่ต้องฝากเลย

    ReplyDelete