1

I'm trying to put user names in string set by using SharedPreferences.putstringset, the problem is that I want to get each name(value) the user put and add it to an arraylist and print each value.

I tried pref.getstringset but I don't know how to do it.

SharedPreferences.Editor editor=pref.edit();
editor.putStringSet("user names",usernames.getText().toString());
editor.commit();
piet.t
  • 11,718
  • 21
  • 43
  • 52

2 Answers2

1

Store the user names in a set like this :-

Set<String> userNames = new HashSet<>();
userNames.add(usernames.getText().toString())

Then put the set in share preferences :-

editor.putStringSet("user names",userNames);
editor.commit();

Then finally get it with a default value and print it :-

for(String name : pref.getStringSet("user names", new HashSet<>()))
    System.out.println(name);
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
  • an error message say(ClassCastException: java.lang.String cannot be cast to java.util.Set at android.app.SharedPreferencesImpl.getStringSet(SharedPreferencesImpl.java:234)).. The compiler was refering to this line of code ( for(String name : pref.getStringSet("user names", new HashSet<>())) System.out.println(name);) – peter Estifanos Aug 14 '19 at 18:22
0
Set<String> fetch = editor.getStringSet("your_key", null);
Iterator value = set.iterator(); 
while (value.hasNext()) { 
   //do whatever you want
   //add to the arraylist

} 
Rohit Suthar
  • 967
  • 9
  • 22