0

Possible Duplicate:
Array of strings in SharedPreferences

I am a new one in Android and would like to study how to save and retrive String[] from Preferences.For now I have two samples of code. This one for saving

    void saveText() {
    sPref = getSharedPreferences("MyPref", MODE_PRIVATE);
    Editor ed = sPref.edit();
    ed.putString(SAVED_TEXT, position_name);
    ed.commit();
}

and position_name came as an EditText input. First, it should be saved in a String array and then String array saved in Preferences. For loading I have the following code

    void loadText() {
    sPref = getSharedPreferences("MyPref", MODE_PRIVATE);
    String position_name = sPref.getString(SAVED_TEXT, "");
    bazar.add(new Bazar(position_name, R.drawable.unread));
}

both methods are static but I want them to work with dynamic String type data. In short I type some data it should be stored in String array then String array stored in Preferences and when I load my activity I want those stored datas to be retrieved. Tried different approaches no result. Can you help me on this.

Community
  • 1
  • 1
user1706819
  • 125
  • 1
  • 4
  • 17

3 Answers3

1

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.

G M Ramesh
  • 3,420
  • 9
  • 37
  • 53
0

You can't as shared prefs only support primitive variables, at least can't for anything under api 11. For lower what you can do is step sort of step through the array and put it individually like here http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html?m=1

What i personally do is I serialize the object which I guess brings it into 0s and 1s. Then you put that in there. You need to get a serialization class or make one yourself Save ArrayList to SharedPreferences

shame on you though. A simple search would've gotten you these results

Community
  • 1
  • 1
mango
  • 5,577
  • 4
  • 29
  • 41
0

save it as string by ,(comma) seperator and while fetching just use split()

string str="";
str += "item1,";
.
.

set String str in your SharePreference and commit() To get the same in array: get prefStr from SharePreference

String[] Array= prefStr.split(",");

Hope it will help you.

Rushabh Patel
  • 3,052
  • 4
  • 26
  • 58