0

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?

Ido Naveh
  • 2,442
  • 3
  • 26
  • 57
  • Use commit() instead of apply() and check if the problem continues – Mohammad Abbas Nov 22 '16 at 10:19
  • Try adding some items to your hash set? – Tomislav Turcic Nov 22 '16 at 10:28
  • Are you totally sure that HomeActivity.AddedItems does equal "AddedItems"? You should use the same static final variable for all these keys. – MSpeed Nov 22 '16 at 10:29
  • Also this whole if statement could be replaced by Set cart = cartItems.getStringSet("AddedItems", new HashSet()); – MSpeed Nov 22 '16 at 10:30
  • @billynomates Yes I'm sure. In `HomeActivity`'s code I've just added " in order to not write the variable but it is defined as `public static final String AddedItems = "AddedItems";`. – Ido Naveh Nov 22 '16 at 10:32
  • @billynomates But what will happen if I didn't added anything to `cart`? I'll get NullPointerException, won't I? – Ido Naveh Nov 22 '16 at 10:33
  • What's the `HomeActivity.cart` you're adding items to? The posted code does not really show that, and `StringSet`s you obtain from `SharedPreferences` are not for you to modify. – laalto Nov 22 '16 at 10:39
  • All the variables in HomeActivity are defined in the class as `public static... `. I've wrote it like that since I've wanted to shpw you the type of every variable – Ido Naveh Nov 22 '16 at 10:41
  • So the problem seems to be that you're modifying the stringset returned by sharedpreferences and you should not be doing that. Clone it before modification. – laalto Nov 22 '16 at 10:51
  • @IdoNaveh No, if there is no value saved in sharedpreferences for that key, it will return the second parameter. So in my example above `cart` will equal `new HashSet()` – MSpeed Nov 22 '16 at 11:00
  • @billynomates I've compiled your solution, but `cart` still resets whenever I open the app – Ido Naveh Nov 22 '16 at 11:17

2 Answers2

0

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/

Varma460
  • 497
  • 1
  • 4
  • 13
  • u have to store cartItems instead of cart and set if(cartItems.getStringSet("AddedItems", null) !=null) – Varma460 Nov 22 '16 at 11:25
  • I've checked your solution again and I found a problem. When I remove everything from the shopping cart, it supposed to be empty, but whenever I reopen the app, it keeps showing me the first item I've added although it supposed to be empty. The same thing happens when there is only one item in the shopping cart. When I reopen the app it keeps showing me the first item I've added to the shopping cart although it wasn't supposed to be there – Ido Naveh Nov 22 '16 at 14:29
0
 public class MainActivity extends AppCompatActivity {

    private final String ADDED_ITEMS = "AddedItems1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Set<String> cart = new HashSet<>();

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

        if (cartItems.getStringSet(ADDED_ITEMS, null) == null) {
            cart.add("hello");
            editor.putStringSet(ADDED_ITEMS, cart);
            editor.apply();
        } else {
            cart = cartItems.getStringSet(ADDED_ITEMS, null);
        }

        Log.d("test", cart.toString()); //put a breakpoint here and look what cart contains
    }
}

I just ran this a few times and it works fine. You mustn't edit what is returned by getStringSet. Get the set from sharedpreferences, assign it to a new variable, then add your new product ID, and then overwrite.

If your HomeActivity.cart is empty when you restart the app, you are only adding one product ID and then overwriting the old values.

So when you are adding a new productID, do this:

cart = cartItems.getStringSet("AddedItems", new HashSet<String>());
cart.add(productId);
editor.putStringSet(HomeActivity.AddedItems, HomeActivity.cart);
editor.apply();

Side note: HomeActivity.cart says to me that you might be using static variables in other classes. Don't do this. You cannot guarantee that they will keep their values if they are not marked as final.

MSpeed
  • 8,153
  • 7
  • 49
  • 61