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.

94 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
  29. 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
  30. Thanks for sharing...Thank you for your post. This is excellent information. oracle training in chennai

    ReplyDelete
  31. GREAT topic! It is really interesting to read from the beginning & I would like to share your blog to my circles, keep sharing…. oracle training in chennai

    ReplyDelete
  32. 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
  33. 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
  34. Did you know that you can easily view the contents of your phone on your TV without a cable? With a screen mirror app you can easily do the screen mirroring from Android to TV. Check out www.screenmirroring.me to find out more.

    ReplyDelete
  35. Want to set your career towards the software field? Then join hands with Infycle Technologies to make this into reality. Infycle Technologies, the best software training center in Chennai, gives the combined and best software training in Chennai, with various stages of multiple courses such as Big Data, Python, Data Science, Oracle, etc., which professional tutors will guide in the field. The Hands-on practical training and the mock interview sessions will be given to the candidates to face the interviews with full confidence. Apart from all, the candidates will be placed in the top MNC's with the highest salary package in the market. To get it all, call 7502633633 and make this happen for your happy life.Best Software Training Institute in Chennai | Infycle Technologies

    ReplyDelete
  36. Worth reading! Our experts also have given detailed inputs about these trainings & courses! Presenting here for your reference. Do checkout
    Aws training in chennai & enjoy learning more about it.

    ReplyDelete
  37. Did you want to set your career towards Oracle? Then Infycle is with you to make this into reality. Infycle Technologies gives the combined and best Oracle course in Chennai, which offers various stages of Oracle such as Oracle PL/SQL, Oracle DBA, etc., along with 100% hands-on training guided by professional tutors in the field. Along with that, the mock interviews will be given to the candidates to face the interviews with complete confidence. Apart from all, the candidates will be placed in the top MNC's with an excellent salary package. To get it all, call 7502633633 and make this happen for your happy life.Best Oracle Training in Chennai | Infycle Technologies

    ReplyDelete
  38. Learn Amazon Web Services for excellent job opportunities from Infycle Technologies, the Excellent AWS Training in Chennai. Infycle Technologies gives the most trustworthy AWS course in Chennai, with full hands-on practical training from professional trainers in the field. Along with that, the placement interviews will be arranged for the candidates, so that, they can meet the job interviews without missing them. To transform your career to the next level, call 7502633633 to Infycle Technologies and grab a free demo to know more

    ReplyDelete
  39. Infycle Technologies is the best software training center in Chennai and is widely known for its excellence in giving the best software training in Chennai. Providing quality software programming training with 100% assured placement & to build a strong career for every individual and young professionals in the software industry is the ultimate aim of Infycle Technologies. Apart from all, the students love the 100% practical training, which is the specialty of Infycle Technologies. To proceed with your career with a solid base, reach Infycle Technologies through 7502633633.
    Best Software Training Center in Chennai | Infycle Technologies

    ReplyDelete
  40. Yuk Gabung di NAGAQQ: AGEN BANDARQ BANDARQ ONLINE ADUQ ONLINE DOMINOQQ TERBAIK

    Yang Merupakan Agen Bandarq, Domino 99, Dan Bandar Poker Online Terpercaya di asia hadir untuk anda semua dengan permainan permainan menarik dan bonus menarik untuk anda semua

    Bonus yang diberikan NagaQQ :
    * Bonus rollingan 0.5%,setiap senin di bagikannya
    * Bonus Refferal 10% + 10%,seumur hidup
    * Bonus Jackpot, yang dapat anda dapatkan dengan mudah
    * Minimal Depo 15.000
    * Minimal WD 20.000

    Games Yang di Hadirkan NagaQQ :
    * Poker Online
    * BandarQ
    * Domino99
    * Bandar Poker
    * Bandar66
    * Sakong
    * Capsa Susun
    * AduQ
    * Perang Bacarrat
    * Perang Dadu
    * BD QQ (New Game)

    Menyediakan deposit Via E-Money
    Seperti : OVO, Dana , Gopay, Link aja ,dll

    Info Lebih lanjut Kunjungi :
    Website : NagaQQ
    Facebook : NagaQQ Official
    Kontakk : Info NagaQQ
    linktree : Agen Judi Online
    WHATSAPP 1 : +855977509035
    Line : Cs_nagaQQ
    TELEGRAM : +855967014811

    ReplyDelete
  41. You made some really goood points there. I looked on the net for more information about the issue and found most people will go along with your views on tis web site. 토토사이트

    ReplyDelete
  42. I get pleasure from, cause I found just what I used to be having a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. 경마

    ReplyDelete
  43. 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
  44. I want to encourage you conttinue
    your great writing, have a nice day! 온라인경마

    ReplyDelete
  45. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Big Data Hadoop Training in Chennai | Infycle Technologies for students, freshers, and tech professionals. Infycle also offers other professional courses such as DevOps, Artificial Intelligence, Cyber Security, Python, Oracle, Java, Power BI, Selenium Testing, Digital Marketing, Data Science, etc., which will be trained with 200% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7502633633 to get more info and a free demo.

    ReplyDelete
  46. Grab the Oracle Certification in Chennai from Infycle Technologies, the best software training institute, and Placement center in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Cyber Security, Big Data, Java, Hadoop, Selenium, Android, and iOS Development, DevOps, 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. Grab Oracle Certification in Chennai | Infycle Technologies

    ReplyDelete



  47. 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


  48. Hey friend, it is very well written article, thank you for the valuable and useful information you provide in this post. Keep up the good work! FYI, please check these depression, stress and anxiety related articles:
    fino partner , The Alchemist book review

    ReplyDelete
  49. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Big Data Hadoop training in Chennai for students, freshers, and tech professionals. Infycle also offers other professional courses such as DevOps, Artificial Intelligence, Cyber Security, Python, Oracle, Java, Power BI, Selenium Testing, Digital Marketing, Data Science, etc., which will be trained with 200% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7502633633 to get more info and a free demo. No.1Big Data Hadoop Training in Chennai | Infycle Technologies

    ReplyDelete
  50. Infycle Technologies, the best software training institute in Chennai offers the No.1 Oracle training in Chennai for students, freshers, and tech professionals. In addition to that, other in-demand courses such as Big Data, Java, Python, Power BI, Digital Marketing will be trained with 100% practical classes. Once the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo. Grab Oracle Training in Chennai | Infycle Technologies

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