7

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 4

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
If 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.
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
2

If you are looking for StringTokenizer then blog post 1 and blog post2 would be helpful

Comments

1

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.

1 Comment

thanks.., ya sure.. some links or code regarding this would be really helpful
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.