如果我知道与之配对的“值”值,是否可以从 SharedPreferences 文件中获取“键”值?
假设我进入了 SharedPreferences 文件,并通过用户操作获得了值“London, UK”。
现在我想获取与“伦敦,英国”值关联的 KEY,然后将其用于下一步,这可能吗?
我现在使用的代码从 SharedPerferences 中获取所有数据,按值排序,用这些数据填充 AlertDialog,处理用户从 AlertDialog 中选择一个选项,然后返回该选项的值。我现在需要与值配对的 KEY。
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();
}