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

后端 未结 2 647
南方客
南方客 2021-01-20 21:20

Is it possible to get the \"key\" value from a SharedPreferences file if I know the \"value\" value it is paired with?

Let\'s say I\'ve gone into the SharedPreferenc

相关标签:
2条回答
  • 2021-01-20 22:08

    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.

    0 讨论(0)
  • 2021-01-20 22:18

    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.

    0 讨论(0)
提交回复
热议问题