How To Store List In SharedPreferences Android

SharedPreferences is a way to store data in application itself. SharedPreferences in android is used to store data on based key value pair. It allows developer to save and retrieve data based on key and value.

In order to invoke SharedPreferences we should call getSharedPreferences() method. In SharedPreferences there are 6 types of mode.

  1. MODE_APPEND
  2. MODE_ENABLE_WRITE_AHEAD_LOGGING
  3. MODE_MULTI_PROCESS
  4. MODE_PRIVATE
  5. MODE_WORLD_READABLE
  6. MODE_WORLD_WRITEABLE

SharedPreferences can only save primitive type of data i.e Int, String, Boolean and hence cannot save non-primitive data i.e ArrayList, Hashmap etc.

In this tutorial I am going to show you how to add non-primitive data type. So let’s start.

We are going to use this library in order to save list in SharedPreferences. Add the below dependency.

You can have a deep look at Link.

Creating User Interface

SharedPreferences_android

  • Add activity_main.xml

Building Android Application

  • Define SharedPreferences in your MainActivity.java

  • Store data in SharedPreferences.

  • Retrieve data from SharedPreferences.

  • Combining it in MainActivity.java

SharedPreferences_list SharedPreferences_list

Now run the android application.

That’s all guys. If you have any query then please free to comment below and I would be happy to help you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.