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

本秂侑毒 提交于 2019-12-02 01:54:21

问题


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 SharedPreferences file and, through a user action, have got the value "London, UK".

Now I want to get the KEY associated with the value "London, UK" and then use that for my next step, is this possible?

The code I use at the moment to getAll data from the SharedPerferences, sort it by value, populate an AlertDialog with this data, deal with a user choosing an option from the AlertDialog and then returning the value of that choice. I now need the KEY that's paired with the value.

public void openServerDialog() {


        final SharedPreferences myPrefs = this.getSharedPreferences("FileName", MODE_PRIVATE);
        TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            Log.i("map values", entry.getKey());
            //some code
        }


      List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
            sortedByValue.add(e);
        }

     // Pair doesn't have a comparator, so you're going to need to write one.
        Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
            public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {

                String sls = String.valueOf(lhs.first);
                String srs = String.valueOf(rhs.first);
                int res = sls.compareTo(srs);
                // Sort on value first, key second
                return res == 0 ? lhs.second.compareTo(rhs.second) : res;
            }
        });

        for (Pair<Object, String> pair : sortedByValue) {
            Log.i("map values", pair.first + "/" + pair.second);
        }


      Collection<?> stringArrayList = keys.values();
      final CharSequence[] prefsCharSequence = stringArrayList.toArray(new CharSequence[stringArrayList.size()]);

        new AlertDialog.Builder(this)   
        .setTitle(R.string.server_title)
        .setItems(prefsCharSequence, 
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialoginterface, int i) {

                setServer(prefsCharSequence[i]);   

            }
        })
        .show();
    }

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12713321/can-i-get-the-key-from-sharedpreferences-if-a-know-the-associated-value

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