Can I get the key from SharedPreferences if a know the associated value?

孤街醉人 提交于 2019-12-01 22:41:30
Brigham

You can use the SharedPreferences.getAll method.

String findKey(SharedPreferences sharedPreferences, String value) {
    for (Map.Entry<String, ?> entry: sharedPreferences.getAll().entrySet()) {
        if (value.equals(entry.getValue())) {
            return entry.getKey();
        }
    }
    return null; // not found
}

You should note that while keys are guaranteed to be unique in SharedPreferences, there's no guarantee that the values will be unique. As such, this function will only return the key for the first matching value.

You can try:

SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);

Iterator iter = prefs.getAll().entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry pair = (Map.Entry)iter.next();
       // Check the value here
    }

You can iterate over that map and look for the value you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!