Shared Preferences loading multiple values

瘦欲@ 提交于 2020-01-17 05:45:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!