首页 文章

从保存在sharedPreferences中的Arraylist <object>中删除一个对象

提问于
浏览
1

你好我一直在寻找一种方法来保存和检索带有自定义对象的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中的一个对象,我该怎么办?

2 回答

  • -1

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

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

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

  • 1

    从代码中已经提到了从SharePreferences获取json并转换为对象部分,如果你知道需要删除的对象CartItem然后是步骤 .

    • CartItem 中覆盖 equals ,这将有助于比较列表中的对象 .

    • Arraylist.conatins(Object) 如果为true则继续并删除它 . ArrayList.remove(Obejct)

相关问题