Search code examples
androidsharedpreferences

Remove Shared preferences key/value pairs


I store some payment values in one Activity

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
productId = spreferences.getString("productId", "");
purchaseToken = spreferences.getString("purchaseToken", "");
orderId = spreferences.getString("orderId", "");

Now I retrieve them in another one as

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
productId = spreferences.getString("productId", "");
purchaseToken = spreferences.getString("purchaseToken", "");
orderId = spreferences.getString("orderId", "");

My question is to delete them in the second Activity after retrieving them.Thanks.


Solution

  • Use SharedPreferences.Editor remove (String key) to do the same.

    where it marks in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called.

    Note that when committing back to the preferences, all removals are done first, regardless of whether you called remove before or after put methods on this editor.


    So in your case you can use it like

    SharedPreferences.Editor editor = spreferences.edit();
    editor.remove("productId");
    editor.remove("purchaseToken");
    editor.remove("orderId");
    editor.commit();