我的sharedPrefs中有一组字符串。我想删除列表中的特定项目
<set name="items">
<string>217372223</string>
<string>222015066</string>
<string>217771052</string>
<string>220431322</string>
所以我想删除说,217372223,但保留其余部分?
答案 0 :(得分:1)
remove(String key)
方法
SharedPreferences sharedPreferences = context.getSharedPreferences("items", Context.MODE_PRIVATE);
sharedPreferences.edit().remove(String key).commit();
确保您的参赛作品有一把钥匙。尝试这样的事情:
<string name="keyToDelete">217372223</string>
然后
sharedPreferences.edit().remove("keyToDelete").commit();
答案 1 :(得分:0)
/**
* 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();
}
这就是我遇到的问题。我从SharedPrefs复制了Set,删除了我想删除的项目,从SharedPrefs中删除了整个集合,然后重新添加了减去我想删除的项目的集合。