0

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?

Ferr0283
  • 1
  • 2

1 Answers1

0

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");
HenriqueMS
  • 3,864
  • 2
  • 30
  • 39
  • @Ferr0283 have you been able to solve your problem? I believe this answer should be marked as correct , let me know if this helped =) – HenriqueMS Oct 17 '16 at 18:20