将ArrayList保存到实现Serialize的共享首选项?

时间:2014-03-16 15:52:39

标签: java android arraylist

我试图将可序列化的ArrayList保存到sharedPreferences。在阅读了许多答案后,我总结使用Serialize是一个可行的替代方案,但我还没有找到任何关于如何做的例子。

如果我的ArrayList是这个:

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();
    }
}

如何从SharedPreferences保存和检索我的ArrayList?

1 个答案:

答案 0 :(得分:0)

尝试使用该实现。 在item方法中实现toString()和构造函数,可以从该字符串构造Item对象。

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();
  }
}

那就是saveList实现:

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();     
    }

为了阅读你可以简单地使用......

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;

}