问题
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