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.
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);