Deleting all but one SharedPreference
Asked Answered
L

5

7

I want to clear all but one SharedPreference. If I've saved 10+, is there a better way then removing each individually? This gets a bit redundant:

preferences.edit().remove("1").commit();
preferences.edit().remove("2").commit();
preferences.edit().remove("3").commit();
...
preferences.edit().remove("15").commit();
Lavone answered 30/4, 2014 at 18:6 Comment(0)
L
20

You could also get the value you want to keep, clear(), and re-add it before commiting.

Lutherlutheran answered 30/4, 2014 at 18:8 Comment(2)
Not bad. Might go with thisLavone
I think this is the best wayPolythene
V
9

you can loop through all the keys

Map<String,?> prefs = pref.getAll();
for(Map.Entry<String,?> prefToReset : prefs.entrySet()){
    edit.remove(prefToReset.getKey()).commit();
}

then skip over the key/s you dont want to remove

Volnay answered 30/4, 2014 at 18:8 Comment(2)
I have to respectfully disagree with a point about this solution: commit() can be expensive, and you'd be executing it n times. It would be much better if that part was moved outside the loop.Lutherlutheran
@Lutherlutheran you can always use apply() which first writes it to memory and then starts an asynchronous commit to diskVolnay
G
0

You can call remove() multiple times before commit().

preferences.edit().remove("1").remove("2")....commit();
Genista answered 30/4, 2014 at 18:7 Comment(1)
Right but that doesn't reduce the number of lines. Anything more elegant?Lavone
G
0

you can do like this ->

private static void clearSp() {

    Map<String, ?> mapPref = sharedPrefObj.getAll();
    if (mapPref.containsKey("key_need_to_retain"))
        mapPref.remove("key_need_to_retain");

    for (Map.Entry<String, ?> prefToRemove: mapPref.entrySet())
        editor.remove(prefToRemove.getKey()).apply();

}
Goodtempered answered 24/3, 2021 at 9:34 Comment(0)
T
0

You can get the value you want to exclude from clear, then call clear(), then re-add it then call commit().

    val valueToKeep = preferences.getInt(
                VALUE_TO_KEEP_KEY,
                0
            )//getting the value first

    preferences.edit().clear()
                .putInt(VALUE_TO_KEEP_KEY, valueToKeep).commit()
Tasker answered 29/5, 2022 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.