1

I'm trying to save a serialiable ArrayList to sharedPreferences. After reading many answers I concluded using Serialize is a viable alternative however I haven't found any examples on how to do it.

Provided my ArrayList is this one:

private ArrayList<Item> addedItems = new ArrayList<Item>();

private class Item {
    private CharSequence title;
    private Class activityClass;

    public Item(int titleResId, Class activityClass) {
        this.title = getResources().getString(titleResId);
        this.activityClass = activityClass;
    }

    @Override
    public String toString() {
        return title.toString();
    }
}

How can I save and retrieve my ArrayList from SharedPreferences?

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

1 Answers1

0

Try using that implementation. Implement in your item method toString() and constructor that can construct your Item object from that string.

public class Item{
   private CharSequence title;
   private Class activityClass;
   public Item(String s){

       String args[] = s.split(',');
       if(args.lengt==2){
         title = args[0];
         activityClass = new Class(args[1]);
       }

   }
public Item(int titleResId, Class activityClass) {
    this.title = getResources().getString(titleResId);
    this.activityClass = activityClass;
}

   @Override
   public String toString(){
     return title.toString() + "," + activityClass.toString();
  }
}

That is saveList implementation:

public boolean saveList(List<Item> list)
    {
        SharedPreferences sp = SharedPreferences.getDefaultSharedPreferences(this);
        SharedPreferences.Editor mEdit1 = sp.edit();
        mEdit1.remove("list"); // be sure that there was no item like that
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0;i<list.size();i++)  
        {
            stringBuffer.append(list.get(i));
            stringBuffer.append(";");
        }
        mEdit1.putString("list",stringBuffer.toString());
        return mEdit1.commit();     
    }

and for reading you can simply use sth like that

public List<Item> loadList(Context mContext)
{  
    Shared Preferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
    List<Item> arrayList = new ArrayList<Item>();
    String arrayString = mSharedPreference1.getInt("list", "");  
    String array[] = arrayString.split(";");
    for(int i=0;i<array.length;i++) 
    {
        list.add(new Item(array[i]));
    }
    return list;

}
RMachnik
  • 3,598
  • 1
  • 34
  • 51
  • what if my list becomes smaller? Won't I be leaving garbage on SharedPreferences? I'll try doing something similar but saving it on a single key – lisovaccaro Mar 16 '14 at 16:29
  • Ok, I understood. Check my answer again I made some changes to keep list on one recrod in shared preferences ;) – RMachnik Mar 16 '14 at 16:34