How to remove some key contain a string from Share

2019-03-04 17:53发布

问题:

My Android SharedPreferences is:

key,value

jhon,usa

xxxpeter,uk

luis,mex

xxxangel,ital

dupont,fran

xxxcharles,belg

...

more lines with xxxname

...

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();
 }

Works! Thank you 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();
    }
}

回答1:

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();
}


回答2:

You can directly remove key-value using following lines, no need to do string check

SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("shared_pref_key").commit();


回答3:

You can use sharedPreferences.getAll() to get all the key/value references on your shared preferences and then iterate through them and remove the ones you want.

SharedPreferences.Editor editor = sharedPreferences.edit();
Map<String, ?> allEntries = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
    String key = entry.getKey();
    if (key.contains("xxx")) {
        editor.remove(key);
    }
    editor.commit();
}