1

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

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

Community
  • 1
  • 1
Ceddy Muhoza
  • 636
  • 3
  • 17
  • 34

2 Answers2

2

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

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).

Giorgio Antonioli
  • 15,771
  • 10
  • 45
  • 70
  • iam using these methods in an async manner, however reading sharedpreferences on UI thread seems to be slow, i think i should use a database or file instead. – Ceddy Muhoza Feb 13 '16 at 21:08
  • @C.B I never recommend to save objects in SP if you don't need. DB is the best way to manage custom models – Giorgio Antonioli Feb 13 '16 at 21:28
-1

Getting the json from SharePreferences and converting into object part is already mentioned in your code, If you know the object CartItem which needs to be deleted then steps.

  1. Override equals in CartItem, That will help in comparing objects inside the list.
  2. Arraylist.conatins(Object) if true then go ahead and delete it. ArrayList.remove(Obejct)
Rupesh
  • 378
  • 7
  • 21