Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting and fetching a StringSet from SharedPreferences?

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.

like image 1000
Razgriz Avatar asked Mar 22 '15 13:03

Razgriz


2 Answers

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);
like image 119
A Honey Bustard Avatar answered Oct 11 '22 07:10

A Honey Bustard


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+.

like image 34
Bill Mote Avatar answered Oct 11 '22 07:10

Bill Mote