Shared Preferences Loading Multiple Values
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
Solution 1:
One way you could do it is the following:
//if you are running the code inside from an ActivityContextcontext=this;
SharedPreferencesuserSharedPrefs= context.getSharedPreferences("USER_NAME_PREFS", MODE_PRIVATE);
SharedPreferencespwdSharedPrefs= 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 = newLinkedList<>();
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");
Post a Comment for "Shared Preferences Loading Multiple Values"