我在我的sharedPrefs中有一组字符串。我想删除列表中的特定项目从SharedPreferences中删除特定项目
<set name="items">
<string>217372223</string>
<string>222015066</string>
<string>217771052</string>
<string>220431322</string>
所以我想删除说,217372223,但保留其余?
我在我的sharedPrefs中有一组字符串。我想删除列表中的特定项目从SharedPreferences中删除特定项目
<set name="items">
<string>217372223</string>
<string>222015066</string>
<string>217771052</string>
<string>220431322</string>
所以我想删除说,217372223,但保留其余?
SharedPreferences sharedPreferences = context.getSharedPreferences("items", Context.MODE_PRIVATE);
sharedPreferences.edit().remove(String key).commit();
的remove(String key)
方法确保您的项目有一个键。尝试是这样的:
<string name="keyToDelete">217372223</string>
然后
sharedPreferences.edit().remove("keyToDelete").commit();
/**
* 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中删除整个集合,然后重新添加集合减去我想删除的项目。
如果我使用 preferences.edit()。remove(“items”)。commit(); 这会删除整个列表吗? – x10sion
@ x10sion在这种情况下,最好使用'clear()',它将删除** all **首选项。 – user1301428
为什么在上面的例子中使用“String key”? – x10sion