Saturday 9 February 2013

Store ArrayList in android SharedPreference

Here I am going to explain how to store arraylist in sharedpreference.
Let's say I have an arraylist as following.

ArrayList<String> myArrayList=new ArrayList<String>();

myArrayList.add("value1");
myArrayList.add("value2");
myArrayList.add("value3");
myArrayList.add("value4");
myArrayList.add("value5");
myArrayList.add("value6");

Store arraylist in sharedpreference

SharedPreference sPrefs=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreference.Editor sEdit=sPrefs.edit();

for(int i=0;i<myArrayList.size();i++)
{
         sEdit.putString("val"+i,myArrayList.get(i);
}
 sEdit.putInt("size",myArrayList.size());
 sEdit.commit();

Retrive arraylist from sharedpreference

I am retriving values in another arraylist

ArrayList<String> myAList=new ArrayList<String>();
int size=sPrefs.getInt("size",0);

for(int j=0;j<size;j++)
{
          myAList.add(sPrefs.getString("val"+j));
}



15 comments:

  1. Thank you!! Now how to delete an article array preferences?

    ReplyDelete
  2. Thank you!! Now how to delete an article array preferences?

    ReplyDelete
  3. myAList.add(sPrefs.getString("val"+j ));

    The above line shows error.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. how can we store integer type data in list?

    ReplyDelete
    Replies
    1. Define your arraylist of type Integer
      ArrayList<Integer> myArrayList=new ArrayList<Integer>();

      Store in sharedpreference
      sEdit.putInt("val");

      Retrieve from sharedpreference
      sPrefs.getInt("val");

      Delete
    2. sir please tell me how can i store multi value array list in shared preferences?

      Delete
  6. Sir how to implement SharedPreference for 2D arraylist or multdimentianal arraylist

    ReplyDelete