I wanna know whether is it possible to store array of string in the SharedPreferences. In my application i want , set of names to be stored. I know this can be done using DB,i just wanna know whether is it possible to save those set of name as array of strings in the SharedPreferences.
4 Answers
You can store set of String using SharedPreferences
in API Level 11 and higher. See getStringSet()
and putStringSet()
ю
In API Level prior to 11 you can use some kind of hack. For example, if you need to store string array under key "stringArray", you can save each string from array using putString
and keys "stringArray.1", "stringArray.2", so on.

- 74,247
- 24
- 188
- 156
-
thanks .... i feel this would definitly help me.But is this good way of storing strings, in general ?? i mean storing set of strings in the shared preferences rather than in DB? – Pravy Jul 20 '11 at 12:47
-
1If you have small array of strings it might be easier to just use `SharedPrefernece`. But if you need large arrays of strings, I'd say DB is the only way to go. Its harder to implement and use, but it would more efficient. – inazaruk Jul 20 '11 at 13:42
-
thank for your suggestion and i found that the SET, data structure ,cannot contain duplicate elements. does it mean that it cannot contain same string more than once?? @inazaruk – Pravy Jul 20 '11 at 13:49
If you are looking for StringTokenizer then blog post 1 and blog post2 would be helpful

- 576
- 4
- 14
It's not possible to store them as an array, but you can concatenate them, and then split them when loading, using StringTokenizer
. I can help with some code, if this will be helpful for you.

- 39,695
- 10
- 113
- 130
-
thanks.., ya sure.. some links or code regarding this would be really helpful – Pravy Jul 20 '11 at 12:48
In shared preferences, you can store the data like key value pairs. What I usually do is to insert all the data then get the key list and iterate through it, set key as anything unique, be it numbers 1,2,3 etc
use
SharedPreference sp = context.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); Map presetDataMap = sp.getAll();
then loop through presetDataMap,
Iterator itt = presetDataMap.keySet().iterator();
hope this helps.

- 243
- 2
- 10