Android - Setting and Fetching a StringSet from SharedPreferences?

二次信任 提交于 2019-12-19 15:25:32

问题


Good day, I am building an Android Application. I want to store a set of strings in the Preferences to order to track who used the application based on their log in information.

I don't want to use a database so I know that I should use SharedPreferences to store a list of people who logged in. I want to be able to reset this list so keeping the individual log in data as Strings and NOT as StringSets is not an option. Using individual Strings means that I'll have to keep another list of those strings just so I can clean them up when I want to. A StringSet is easier to maintain.

Here's what I did thus far:

    //this is my preferences variable
    SharedPreferences prefs = getSharedPreferences("packageName", MODE_PRIVATE);

    //I create a StringSet then add elements to it
    Set<String> set = new HashSet<String>();

    set.add("test 1");
    set.add("test 2");
    set.add("test 3");

    //I edit the prefs and add my string set and label it as "List"
    prefs.edit().putStringSet("List", set);

    //I commit the edit I made
    prefs.edit().commit();

    //I create another Set, then I fetch List from my prefs file
    Set<String> fetch = prefs.getStringSet("List", null);

    //I then convert it to an Array List and try to see if I got the values 
    List<String> list = new ArrayList<String>(fetch);

    for(int i = 0 ; i < list.size() ; i++){
        Log.d("fetching values", "fetch value " + list.get(i));
    }

However, it turns out that the Set<String> fetch was null and I'm having a null pointer exception and it's probably because I wasn't storing or fetching my StringSet properly.

Can anyone help me with my problem? I'm dumbfounded and I feel like I'm overlooking something simple. Any help is very much appreciated. Thank you.


回答1:


Create an editor Object first :

SharedPreferences.Editor editor = prefs.edit();

And use the editor object to store and fetch your string set like this :

editor.putStringSet("List", set);
editor.apply();

Set<String> fetch = editor.getStringSet("List", null);



回答2:


You could write your results to a JSON String and store them in Shared Preferences like this: https://stackoverflow.com/a/5968562/617044

But if you choose to go down the route you're currently on then you're going to have to store a parcelable.

As noted in another answer; you can use putStringSet(), getStringSet() if you're building for API 11+.



来源:https://stackoverflow.com/questions/29195164/android-setting-and-fetching-a-stringset-from-sharedpreferences

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