1

While working on my app, I discovered that the only way to save a number of values (like an array) in shared preferences is by using a set. The problem is, that since the whole set thing is new to me, I don't really know how to retrieve values from it, and placing the values in dynamic text views. I would be glad if someone could show me the correct way of retrieving the values.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Ofek Orgad
  • 15
  • 5
  • You could use JSON and serialize most objects to a string. Then you can store strings instead of sets. Then you can deserialize later to get your object back – OneCricketeer May 27 '16 at 23:14

1 Answers1

1

you can find your answer here : Follow the link

From API level 11 you can use the putStringSet and getStringSet to store/retrieve string sets:

SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();

SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set<String> someStringSet = pref.getStringSet(SOME_KEY);

The set interface has method which are as follows :

add() : Which allow to add an object to the collection..
clear() : Remove all object from the collection.
size() : Return the size of element of collection.
isEmpty() : Return true if the collection has element.
iterator() : Return an iterator object which is used to retrieve element from collection.
contains() : Returns true if the element is from specified collection.

Example of java set interface.

Set s=new TreeSet();
        s.add(10);
        s.add(30);
        s.add(98);
        s.add(80);
        s.add(10); //duplicate value 
        s.add(99);
        Iterator it=s.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
Community
  • 1
  • 1
Sir1
  • 732
  • 1
  • 8
  • 18