从 Arraylist<object> 中删除一个对象保存在 sharedPreferences [英] Remove one object from Arraylist&lt;object&gt; saved in sharedPreferences

查看:20
本文介绍了从 Arraylist<object> 中删除一个对象保存在 sharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我一直在寻找一种方法来将带有自定义对象的 Arraylist 保存和检索到 android Sharedpreferences 中.幸运的是,我有办法使用此答案

Hello all along i was looking for a way to save and retrieve an Arraylist with custom object into android Sharedpreferences. Lucky enough i got a way to do it using this 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中的一个对象,我该怎么做?

Now here comes a part where i want to only delete one of the object in the arraylist, how can i do it?

推荐答案

你可以读取数组,移除元素并保存回来:

You can read the array, remove the element and save it back:

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

附言如果您没有认真同步执行此方法的动机,我建议您将保存方法中的 commit() 替换为 apply()(保存将是异步的所以).

P.s. If you haven't a serious motivation to do this method synchronously, I recommend you to replace commit() with apply() in your save method (the save will be async so).

这篇关于从 Arraylist<object> 中删除一个对象保存在 sharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆