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();
}
You can try:
You can iterate over that map and look for the value you want.
You can use the
SharedPreferences.getAll
method.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.