Can I get the key from SharedPreferences if a know

2019-02-24 18:50发布

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();
    }

2条回答
放荡不羁爱自由
2楼-- · 2019-02-24 19:36

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.

查看更多
Juvenile、少年°
3楼-- · 2019-02-24 19:37

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.

查看更多
登录 后发表回答