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.
Asked
Active
Viewed 2,155 times
1
-
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 Answers
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());
}
-
-
I already know how to get the set itself, but the thing that i don't know is how to get the values that are inside the set. – Ofek Orgad May 28 '16 at 09:15
-
I have edited the answer. Hope to be useful. better to read about java Collection. every java programmer need to learn them. good luck – Sir1 May 28 '16 at 10:29
-