displayname950123
displayname950123

Reputation: 11

Shared Preferences for Arraylist

I've a bunch of strings in an arraylist.

I want to save some of the strings in a shared preferences.

like if user selects a sting whose index is 3, I want to store that particular string in a shared preference.

Is it possible?

Please let me know.

Upvotes: 1

Views: 544

Answers (2)

Taldakus
Taldakus

Reputation: 715

To save data to SharedPreferences:

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

   for(int i=0; i<arraylist.size(); i++){
      sharedPreferences.edit().putString("TAG" +  Integer.toString(i)
                                         ,arraylist.get(i)).apply();
    }

To get data from SharedPreferences:

   sharedPreferences.getString("TAG" + "x", null); x is a number position in array list

Upvotes: 0

user2413972
user2413972

Reputation: 1355

I hope that this code will help you understand it

int id = selectedItemNum;

ArrayList<String> list = new ArrayList<String>();
list.add("Item1");
list.add("Item2");
list.add("Item3");
list.add("Item4");
String selectedString = list.get(id);

String APP_PREFERENCES = "savedStrings"; 
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = mySharedPreferences.edit();
editor.putString("savedString"+id, selectedString);
editor.apply();

Upvotes: 2

Related Questions