本文介绍了如何从SharedPreferences中删除一些包含字符串的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的Android SharedPreferences是:
My Android SharedPreferences is:
键,值
美国,jhon
xxxpeter,uk
xxxpeter,uk
luis,mex
xxxangel,ital
xxxangel,ital
都彭,弗兰
xxxcharles,belg
xxxcharles,belg
...
更多行带有xxxname
more lines with xxxname
...
如何删除键中包含xxx的键/值(或以xxx开头).这是我到目前为止所得到的:
How can I delete key/value what contain (or start) with xxx in key. This is what I got so far:
public void Deletekeyxxx() {
final SharedPreferences.Editor sped = sharedPreferences.edit();
if(sped.contains("xxx")){
sped.remove(sped.contains("xxx"));
}
sped.commit();
}
可行!谢谢Ben P.
public void Deletekeyxxx() {
final SharedPreferences.Editor sharedPrefsEditor = sharedPreferences.edit();
Map<String, ?> allEntries = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
String key = entry.getKey();
if (key.contains("xxx")) {
sharedPrefsEditor.remove(key);
}
sharedPrefsEditor.commit();
}
}
推荐答案
您可以使用 SharedPreferences.getAll()
检索Map<String,?>
,然后使用Map.keySet()
遍历键.也许是这样的:
You can use SharedPreferences.getAll()
to retrieve a Map<String,?>
, and then use Map.keySet()
to iterate over the keys. Maybe something like this:
private void removeBadKeys() {
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
SharedPreferences.Editor editor = preferences.edit();
for (String key : preferences.getAll().keySet()) {
if (key.startsWith("xxx")) {
editor.remove(key);
}
}
editor.commit();
}
这篇关于如何从SharedPreferences中删除一些包含字符串的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!