Skip to content Skip to sidebar Skip to footer

How To Remove Some Key Contain A String From SharedPreferences?

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 c

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

Solution 2:

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

Solution 3:

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

Post a Comment for "How To Remove Some Key Contain A String From SharedPreferences?"