1

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.

2 Answers2

2

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();
user2413972
  • 1,355
  • 2
  • 9
  • 25
0

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
Taldakus
  • 705
  • 2
  • 8
  • 18