Ido Naveh Ido Naveh - 18 days ago 7
Java Question

SharedPreferences clears itself when the app opens

I've added SharedPreferences to my

HomeActivity.java
, in order to save IDs for shopping cart. This is the code which I've initialized for it in
HomeActivity.java
, which is the launcher activity:

SharedPreferences cartItems = getSharedPreferences("AddedItems", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = cartItems.edit();
if (cartItems.getStringSet("AddedItems", null) == null){
Set<String> cart = new HashSet<String>();
editor.putStringSet("AddedItems", cart);
editor.apply();
} else {
Set<String> cart = cartItems.getStringSet("AddedItems", null);
}


As you can see, the code supposed to check if
cartItems.getStringSet("AddedItems", null)
is exist. If it does exist, then it sets
cart
to the contents of
cartItems.getStringSet("AddedItems", null)
, but if it doesn't exist, then it defines
cart
as a new
HashSet<String>
and adds it to
cartItems
SharedPreferences.

For some reason, it is probably thinks that
cartItems.getStringSet("AddedItems")
does equal to null, so it resets it every time the app opens and the IDs in cart aren't being saved.

This is how I add ID to the SharedPreferences:

HomeActivity.cart.add(productId);
HomeActivity.editor.putStringSet(HomeActivity.AddedItems, HomeActivity.cart);
HomeActivity.editor.apply();


How can I fix that so It won't reset
cartItems.getStringSet("AddedItems")
every time the app opens?

Answer

Try this :

SharedPreferences cartItems = getSharedPreferences("AddedItems", Context.MODE_PRIVATE); SharedPreferences.Editor editor = cartItems.edit();

    if (Storedata != null){
        editor.putStringSet("AddedItems", Storedata);
        editor.commit();
    } else {
        Set<String> cart = cartItems.getStringSet("AddedItems", null);
    }

Storedata is the ID's of cart you want to save.

Check this for your reference: http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/