Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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();
    }
}
like image 217
canel Avatar asked Dec 23 '22 15:12

canel


2 Answers

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();
}
like image 164
Ben P. Avatar answered Mar 16 '23 00:03

Ben P.


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();
} 
like image 38
Natan Avatar answered Mar 16 '23 01:03

Natan