Remove a specific item from a Set in Sharedpreferences

冷暖自知 提交于 2019-12-13 02:01:56

问题


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

<set name="items">
<string>217372223</string>
<string>222015066</string>
<string>217771052</string>
<string>220431322</string>

So I would like to just remove say, 217372223 but keep the rest?


回答1:


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

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

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

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

and then

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



回答2:


    /**
   * Deletes a particular value or FULL Set from shared preferences.
   *
   * @param key
   */
  public static void deleteValueInPreferences(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.
   *
   * @param key
   */
  public static void deleteSingleValueInSetInPreferences(Context context, String key, String value) {
    Set<String> aSetOfExistingStrings = getStringArrayFromPreferences(context, key);
    deleteValueInPreferences(context, key);
    Set<String> aNewSetOfExistingStrings = new HashSet<String>();
    aNewSetOfExistingStrings.addAll(aSetOfExistingStrings);
    aNewSetOfExistingStrings.remove(value);
    setStringArrayIntoPreferences(context, key, aNewSetOfExistingStrings);
  }
  /**
   * @param context
   * @param key - Set Key
   * @param keyValueMap - Set Key List
   */
  public static void setStringArrayIntoPreferences(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.



来源:https://stackoverflow.com/questions/35843240/remove-a-specific-item-from-a-set-in-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!