Q:

Adding an item to arralist which is already saved in shared preferences in android

I am having an array list which is already stored in shared preferences.I want to add another item in array list.
Whenever i am trying to add an item in array list it is removing all the previous data stored in arraylist
How can i add item without removing the previous data in shared preferences 
ArrayList<String> cartArrayListID,cartArrayListName,cartArrayListPrice,cartArrayListImage;
    String cartID,cartName,cartPrice,cartImage;
cartArrayListID=new ArrayList<>();
        cartArrayListName=new ArrayList<>();
        cartArrayListPrice=new ArrayList<>();
        cartArrayListImage=new ArrayList<>();
cartArrayListID.add(cartID);
                cartArrayListName.add(cartName);
                cartArrayListPrice.add(cartPrice);
                cartArrayListImage.add(cartImage);
SharedPreferences sprefCart=getSharedPreferences("CARTINFO", Context.MODE_PRIVATE);
                SharedPreferences.Editor editorCart=sprefCart.edit();
                Gson gson = new Gson();
                String id_=gson.toJson(cartArrayListID);
                String name_=gson.toJson(cartArrayListName);
                String price_=gson.toJson(cartArrayListPrice);
                String image_=gson.toJson(cartArrayListImage);
                editorCart.putString("ID", id_);
                editorCart.putString("NAME", name_);
                editorCart.putString("PRICE", price_);
                editorCart.putString("IMAGE", image_);
                editorCart.apply();
                Toast.makeText(ProductActivity.this, "Added to cart", Toast.LENGTH_SHORT).show();

A:

as I see in your code, you create a whole new ArrayLists cartArrayListID, cartArrayListName , ..etc everytime, and then you put the new  value into it, after that you save it in SharedPreferences which in turn will replace the old one saved in it with your new one, so you have to:

get the corresponding ArrayList from Shared preferences at first.(for ex. cartArrayListName)
save it in a new array called cartArrayListID.
put the new values in this new array.
save it back in SharedPreferences.

