问题
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?
回答1:
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);
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());
want to know if there's a password for user john?
boolean johnHasPasswd = pwdHashMap.containsKey("john");
String johnsPass;
if(johnHasPasswd)
johnsPass = pwdHashMap.get("john");
来源:https://stackoverflow.com/questions/40028635/shared-preferences-loading-multiple-values