加载多个值的共享首选项 [英] Shared Preferences loading multiple values
问题描述
我目前将用户名和密码保存在不同的共享首选项文件中.我想加载保存在 XML 文件中的每个值,而不仅仅是第一个.这要怎么写?
I currently am saving usernames and passwords in different shared preferences files. I want to load every value saved in the XML file, not just the first. How would this be written?
推荐答案
您可以通过以下方式做到这一点:
One way you could do it is the following:
//if you are running the code inside from an Activity
Context context = this;
SharedPreferences userSharedPrefs = context.getSharedPreferences("USER_NAME_PREFS", MODE_PRIVATE);
SharedPreferences pwdSharedPrefs = context.getSharedPreferences("PWD_PREFS", MODE_PRIVATE);
getAll() 方法将返回一个名为 HashMap
的数据结构,其工作方式类似于字典:
The method getAll() will return a data structure called HashMap
which works like a dictionary:
对于存储的每个值,都有一个唯一键.
For each value stored there is a unique key.
旁注:通过一次获取它们,您有点违反了此数据结构的目的,但让我们继续
sidenote: By getting them all at once you are kinda breaking the purpose of this data structure but let's continue
Map<String, String> userNameHashMap = (Map<String, String>)userSharedPrefs.getAll();
Map<String, String> pwdHashMap = (Map<String, String>)pwdSharedPrefs.getAll();
然后你可以对他们做任何你想做的事情
then you can do whatever you want with them
想要它们在列表中吗?(顺便说一下,我假设您的用户名是字符串)
want them in a list? (I am assuming your user names are strings by the way)
List<String> userNameList = new LinkedList<>();
userNameList.addAll(userNameHashMap.values());
想知道用户 john 是否有密码?
want to know if there's a password for user john?
boolean johnHasPasswd = pwdHashMap.containsKey("john");
String johnsPass;
if(johnHasPasswd)
johnsPass = pwdHashMap.get("john");
这篇关于加载多个值的共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!