android – 如果知道相关值,我可以从SharedPreferences获取密钥吗?
作者:互联网
如果我知道它与之配对的“值”值,是否可以从SharedPreferences文件中获取“key”值?
假设我已进入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();
}
解决方法:
您可以使用SharedPreferences.getAll方法.
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
}
您应该注意,虽然在SharedPreferences中保证密钥是唯一的,但不能保证这些值是唯一的.因此,此函数仅返回第一个匹配值的键.
标签:android,sharedpreferences,key-value 来源: https://codeday.me/bug/20190718/1494649.html