Skip to content Skip to sidebar Skip to footer

Remove A Specific Item From A Set In Sharedpreferences

I have a Set of Strings in my sharedPrefs. I would like to remove a specific item in the list 21737222322201506

Solution 1:

You can use the remove(String key) method of SharedPreferences.Editor

SharedPreferences sharedPreferences = context.getSharedPreferences("items", Context.MODE_PRIVATE);
sharedPreferences.edit().remove(Stringkey).commit();

Make sure your entry has a key. Try something like this:

<string name="keyToDelete">217372223</string>

and then

sharedPreferences.edit().remove("keyToDelete").commit();

Solution 2:

/**
   * Deletes a particular value or FULL Set from shared preferences.
   *
   * @paramkey
   */publicstaticvoiddeleteValueInPreferences(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(SHARED_PREF_FILE_NAME, MODE_PRIVATE);
    if (sp.contains(key)) {
      sp.edit().remove(key).apply();
    }
  }

  /**
   * Deletes a particular value in Set from shared preferences.
   *
   * @paramkey
   */publicstaticvoiddeleteSingleValueInSetInPreferences(Context context, String key, String value) {
    Set<String> aSetOfExistingStrings = getStringArrayFromPreferences(context, key);
    deleteValueInPreferences(context, key);
    Set<String> aNewSetOfExistingStrings = newHashSet<String>();
    aNewSetOfExistingStrings.addAll(aSetOfExistingStrings);
    aNewSetOfExistingStrings.remove(value);
    setStringArrayIntoPreferences(context, key, aNewSetOfExistingStrings);
  }
  /**
   * @paramcontext
   * @paramkey - Set Key
   * @paramkeyValueMap - Set Key List
   */publicstaticvoidsetStringArrayIntoPreferences(Context context, String key, Set<String> keyValueMap) {
    SharedPreferences sp = context.getSharedPreferences(SHARED_PREF_FILE_NAME, MODE_PRIVATE);
    for (String s : keyValueMap) {
    }
    sp.edit().putStringSet(key, keyValueMap).apply();
  }

This is how I over came the issue I was having. I copied the Set from SharedPrefs, removed the item I wanted to remove, removed the whole set from SharedPrefs, then re-added the set minus the item I wanted removed.

Post a Comment for "Remove A Specific Item From A Set In Sharedpreferences"