【问题标题】:Save ArrayList to shared preferences implementing Serialize?将 ArrayList 保存到实现序列化的共享首选项?
【发布时间】:2014-03-16 15:52:38
【问题描述】:

我正在尝试将可串行化的 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?

【问题讨论】:

标签: java android arraylist


【解决方案1】:

尝试使用该实现。 在您的 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;

}

【讨论】:

  • 如果我的列表变小了怎么办?我不会在 SharedPreferences 上留下垃圾吗?我会尝试做类似的事情,但将其保存在一个键上
  • 好的,我明白了。再次检查我的答案我做了一些更改以将列表保留在共享首选项中的一个记录中;)
猜你喜欢
  • 2013-07-27
  • 1970-01-01
  • 2015-07-19
  • 2022-01-15
  • 2014-01-11
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 2011-12-18
相关资源
最近更新 更多