【问题标题】:Remove one object from Arraylist<object> saved in sharedPreferences从 sharedPreferences 中保存的 Arraylist<object> 中删除一个对象
【发布时间】:2016-02-13 19:34:13
【问题描述】:

你好,我一直在寻找一种方法来保存和检索带有自定义对象的 Arraylist 到 android Sharedpreferences 中。幸运的是,我有办法使用这个Answer

public  void saveArray(ArrayList<CartItem> sKey)
{
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    SharedPreferences.Editor mEdit1 = sp.edit();

        Gson gson = new Gson();
        String json = gson.toJson(sKey);
        mEdit1.putString("itemx", json);
        mEdit1.commit();
}

public ArrayList<CartItem> readArray(){
  SharedPreferences appSharedPrefs = PreferenceManager
          .getDefaultSharedPreferences(this.getApplicationContext());
  String json = appSharedPrefs.getString("itemx", "");
  Gson gson = new Gson();
  Type type = new TypeToken<ArrayList<CartItem>>(){}.getType();
  ArrayList<CartItem> List = gson.fromJson(json, type);

  return List;
 }

现在有一部分我只想删除arraylist中的一个对象,我该怎么做?

【问题讨论】:

  • 从 SharedPreferences 中获取到 string 并用 Gson 解析到 Array,删除该项并再次保存到 SharedPreferences 中。
  • @ddog 你能告诉我一些示例代码吗
  • 如何确定要从 ArrayList 中删除哪个对象?在那之后你想做点什么吗?

标签: java android arraylist sharedpreferences


【解决方案1】:

您可以读取数组,删除元素并将其保存回来:

public void removeElement(CartItem item) {
    ArrayList<CartItem> items = readArray();
    items.remove(item);
    saveArray(items);
}

附:如果您没有强烈的动机同步执行此方法,我建议您在保存方法中将commit() 替换为apply()(保存将是异步的)。

【讨论】:

  • iam 以异步方式使用这些方法,但是在 UI 线程上读取 sharedpreferences 似乎很慢,我认为我应该改用数据库或文件。
  • @C.B 如果您不需要,我从不建议将对象保存在 SP 中。 DB 是管理自定义模型的最佳方式
【解决方案2】:

您的代码中已经提到从 SharePreferences 获取 json 并转换为对象部分,如果您知道需要删除的对象 CartItem 则步骤。

  1. CartItem 中覆盖equals,这将有助于比较列表中的对象。
  2. Arraylist.conatins(Object) 如果为真,则继续删除它。 ArrayList.remove(Obejct)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2016-03-11
    • 2016-02-14
    • 1970-01-01
    • 2013-05-29
    • 2016-07-01
    相关资源
    最近更新 更多