且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从SharedPreferences中删除一些包含字符串的键?

更新时间:2023-11-14 11:05:22

您可以使用 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();
}