Android: How to store list of values in SharedPreferences

In almost all our applications we are required to store application related user preferences or settings like favorites, language settings etc. Android provides a lot of options for storing data but the preference related settings can be easily stored and maintained using SharedPreferences class.

In this Android example, we will see how to store multiple or list of values in SharedPreferences under same key and retrieve values from it. To explain this concept, we display a list of items with favorites icon. When the list item is long pressed, the item is added to the favorites. When we say the item is added to the favorites, we actually store the list of items in shared preferences mapped to a key.

Android SharedPreferences class does not provide a way to store a List or ArrayList or any collection. In order to store a list (even array, set or any collection) under a key, we convert the list (or collection) to JSON format using Gson and store it as string. While retrieving we convert the JSON string back to list and return it.

1.android-sharedpreferences-favorites

In this Android SharedPreferences tutorial we will be doing the following,

  • Create a separate SharedPreference utility class with methods to save, add, remove and get favorites from SharedPreferences.
  • Display list of products in ListView in list fragment. When a list item is long pressed, it is added to favorites list stored in SharedPreferences.
  • Add an Action bar favorite menu item icon to display all the stored favorite items in a ListView. FavoriteListFragment is used to display this ListView. When an item is long pressed in this ListView it is removed from favorites i.e.) removed from SharedPreferences.

Android Project

Create a new Android project and name it as SharedPreferencesFavorites.

Download “Android SharedPreferences Storing Favorites” SharedPreferenceDemo.zip – Downloaded 5987 times – 2 MB

Resources

colors.xml

Create a new file res/values/colors.xml and copy paste the following content.

strings.xml

Open res/values/strings.xml and edit to have the content as shown below.

strings_fav_msg.xml

Create a new file res/values/strings_fav_msg.xml and copy paste the following content. This file defines string messages related to favourites.

Action Bar Menu Item (main.xml)

Open res/menu/main.xml and edit to have the content as shown below. When this menu item is clicked, it displays FavoriteListFragment.

Layout Files

activity_main.xml

This layout file defines Framelayout which holds all fragments. Open res/layout/activity_main.xml and edit to have the content as shown below.

fragment_product_list.xml

This layout file defines a ListView which is used by ProductListFragment to display list of products.

product_list_item.xml

This file defines custom layout for ListView item which is used by ProductListAdapter.

Source files

Product

In src folder, create a new class Product in the package com.androidopentutorials.spfavorites.beans. This class represents a Product displayed in the ListView.

SharedPreference class

Create a new class SharedPreference in the package com.androidopentutorials.spfavorites.utils. This class defines methods to save, add, remove and get favorites from SharedPreferences.

Here we use Gson to convert List to JSON string in saveFavorites method and back again to List in getFavorites method.

ProductListAdapter

In src folder, create a new class ProductListAdapter in the package com.androidopentutorials.spfavorites.adapter. This is the custom list adapter class which displays product name, description, price and favorite icon.

ProductListFragment

In src folder, create a new class ProductListFragment in the package com.androidopentutorials.spfavorites.fragment.

  • This class displays list of products.
  • On item long click it adds that product in favorites by saving it in SharedPreferences. If the same item is long clicked again it is removed from favorites.

FavoriteListFragment

In src folder, create a new class FavoriteListFragment in the package com.androidopentutorials.spfavorites.fragment.

  • This fragment displays all the stored favorite items in a ListView. When an item is long pressed in this ListView it is removed from favorites i.e.) removed from SharedPreferences.
  • This fragment is displayed when favorite icon in Action bar is clicked.

MainActivity

This is the main activity class.

  • When the app starts, it begins a new FragmentTransaction and starts ProductListFragment.
  • When an Action bar icon is clicked, it starts FavoriteListFragment.
  • Proper back navigation of fragments on back key pressed is handled by overriding onBackPressed()
  • It also handles fragment orientation changes and retains the state of the fragment by overriding onSaveInstanceState()

Output

ProductListFragment screen

1.android-sharedpreferences-favorites

FavoriteListFragment screen

2.android-sharedpreferences-favorites

  • Shruti Goyal

    Hi.. this method being very useful to me… but it is causing exception when i try to add a item to favorite second time, it gives me below mentioned error :-

    java.lang.IllegalArgumentException

    at com.google.gson.internal.$Gson$Preconditions.checkArgument($Gson$Preconditions.java:42)

    this execption occurs at “String jsonFavorites = gson.toJson(favorites);”

    Please tell me what i am doing worng, and what is the other approach i have to follow not to get this error.

    • zohain

      I do not know about the Gson.
      why you convert to Gson. is without this saving is not possible?

  • Sadat Mohammad Akash

    Hi I have some problem in MainActivity. There is a function switchContent which takes fragment as parameter. But there is a line where ProductListFragment which is another class is being sent…?

  • Mayank Langalia

    HEy Friends I have some problm, when i scroll down icon change. what should i do ?

  • Om Balakumar

    hi guys, I have used this code for my project, I have a viewpager inside tabs of fragments, in first fragment,Insert of list i have used gridview and add images and favorite icon too. All works perfectly,But For example i like to add first image as favorite and i am longclick it and the image added in Favorites. Okay. Now i am going to favorites page the favorited image is present. When i again come back all images favorite icon becomes red. Can anyone help me guys..

    • Mohamed Abdiqadir Osman

      can you share the code please am having trouble adding the viewpager with tab

  • Dušan Dimitrijević

    I know that this tutorial has written long before, but i’m having a problem with making this to work. I’m trying to do this with recyclerview and the problem i’m experiencing is that when i add to favorite some item and scroll down and come back up, recycler deselect favorite and looses that state. It is also happens when i exit from app and come back and nothing is store in sharedPreference because when i go to the activity where should i see favorites i’m always getting alert dialog that there are no favorites yet.

  • m33ts4k0z

    Thanks for this. As of 30 April 2016, this still works great but needs some slight adaptations. First, in the MainActivity class, its better to extend to AppCompatActivity instead of FragmentActivity. Then the getActionBar() call should be changed to getSupportActionBar() if you add the toolbar programmatically. I use a theme based toolbar so using this method to change the title won’t work. setTitle() will suffice if we want to set the title of the current fragmented activity on the toolbar.

    • Chuy David Garza Dovalina

      Hello sir, i have a problem with that too, it doesn’t show me the bar with the button, can you give a screenshot of that pls!!!! thanks P.S: sorry for my bad english :)

  • FaisalHyder

    Hi there nice one, but how to make it work with recycler view, items are getting added in favourite shared preferences but not getting deleted from it and lot of duplicate items plus list removes selected heart on app restart from all selected items of main recycler list while they are still present in favorite shared preference..
    any one done it using RecylerView?

    • FaisalHyder

      :) I have solved it :)

      • khanZee

        hi . can u please tell how did u solve this issue? even i am gettin duplicate items and slected heart is resetting on back press. any help is really appreciated :) thanks!

        • FaisalHyder

          I can tell you the approach, it is simple, i click on recycler view’s item i.e imagebutton, i am handling clicks of both main activity and favourite activity separately from them, when i click on imagebutton it takes main string field puts it in array and saves the arrayList in sharedpreferences, on fetching back i am taking that list and searching RLV’s items in that List inside recycler adapter to put star on selected items, then from clicking on that imagebutton i once again search the list item from sharedpreferences if it exists , i remove it and update list…. i will put its git code tomorrow, in sha Allah, you can check it from there :)

          • khanZee

            thank you so much bhai! the info is appreciated.. please do upload it on git.. counting on you.. jazak allah

          • FaisalHyder

            I have added it, github.com/mfaisalhyder :) no problem, you can improve code a lot, i deliberately have uploaded older version, where there is bug in recycler adapter that it removes element from Mainactivity as well :D try to fix it else i will upload fixed version ;) #learn :D

  • Maham Khan

    Found error in this line
    getActionBar().setTitle(resourseId);
    setFragmentTitle(R.string.app_name);

    • David Pilco

      me too .. u got the answer?

      • Maham Khan

        Thankyou it is working now

  • vinod

    your tutorial is very well. mam, how to implement add to cart using mysql in recyclerview and cardview in android

  • Mohamed Abdiqadir Osman

    great tutorial but can you tell me how to add that a viewpager with tablayout

  • Hillarie Kip

    Hello…i want help as how can you open activities from the favorite list you created

    • Jordan Adcock

      Looks like we will never get a response on this, it’s a great set up but the only thing I’ve figured out for opening a new activity from both the favorites and product list is to do the following.. Not sure if I’m on to something but I just tested it and it works but doesn’t work at the same time.
      So under the private void set products where all the products are listed, onItemClick is shown…Copy this and paste it inside @Override
      public void onItemClick(AdapterView parent, View view, int position,
      long id) {
      Intent intent = new Intent(getActivity(), Main2Activity.class);
      intent.putExtra(“Cheese”,productListView.getItemAtPosition(position).toString());
      startActivity(intent);
      Create a new blank activity…
      Toolbar toolbarcookingguide;
      TextView textviewinstructions;
      ImageView imageviewtemp;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      toolbarcookingguide = (Toolbar) findViewById(R.id.toolbart);
      textviewinstructions = (TextView) findViewById(R.id.textviewinstructions);
      imageviewtemp = (ImageView) findViewById(R.id.imageviewtemp);

      Bundle bundle = getIntent().getExtras();
      if (bundle != null) {
      toolbarcookingguide.setTitle(bundle.getString(“Cheese”));
      ///////For every item set this//////////////////////
      {
      if (toolbarcookingguide.getTitle().toString().equalsIgnoreCase(“product1″)) {
      textviewinstructions.setText(R.string.happy);

      ////////1////////
      }
      if (toolbarcookingguide.getTitle().toString().equalsIgnoreCase(“product2″)) {
      textviewinstructions.setText(R.string.bull);

      ////////1////////

      Thisi is what it should look like, but after equalsIgnoreCase doesn’t work because the way this person set this up, they set the string within the fragment and I’m not sure how to call the title (item name) of each.. When I do this in a regular or custom listview and set the string inside a string folder, each one does it’s own action. SO if I had

      product1
      product2

      product 1 and product 2 would open a textview (xml activity_main2 has a textview template) and list the items that are inside the strings happy and bull. So for example is product 1 was clicked product1 would display the textview of happy string.

      So in this I’m not sure how to call the title of each product becasue they are all laid out in a fragment, and the only thing that is happening is the product id name description price etc shows up on the toolbar, but shows as Product[id=1,name=DellXPS etc……
      How do I set a get extra intent so that each product lists it’s own description……….

      THKKKKKKKKKKKKKKKKKKKKKS

  • Jordan Adcock

    I’ve tried solving how to set an id or something to each one of the products so once the user clicks on Dell in both favorites and product list they go to a Dell activity that lists all Dell products… This is great for learning how to implement a favorites but I want to be able to let the user once the item is in their favorites folder be able to click on the item in their favorites and open an activity that belongs to that item.. So let say I’ve favorited Dell, HP, and IdeaPad, and later in the week I went to my favorites list and clicked on Dell or HP or IdeaPad, i’d like to be able to open different activities with each product..

    Thanks to anyone that knows what I mean and perhaps has the source code

  • Jordan Adcock

    Figured out how to set listeners and getsame resources from main list to favorites list YAYYYYYYYYYYY took me a frigging week to figure it out.. LOVE HOW NO ONE REPLIED STILL

    • Girl Candy (Girlcandy)

      can you please share the code :)

  • Love Songs

    where is SherlockActivity class? You did not provide and result in errors

  • Girl Candy (Girlcandy)

    if the activity was closed, does the favorites you have selected will be saved or not?

    • Jordan Adcock

      Hi Girl Candy, when I get home on Monday I will provide the code for you. Yes it saves even once the application is closed completely. You basically have tp set up a separate fragment for the favourites. I will explain more when I’m home. Take care.

  • yilber esteban flor orozco

    I can not make it work in Android Studio!!!
    can you help me, with the code?