2

I have one "ArrayList> List_Data =new ArrayList>();"

but my requirement is to store that List_Data into sharedpreference . Please Help me out.

3 Answers3

6

Convert your array or object to JSON and store into shared pref

for storing:

SharedPreferences db=PreferenceManager.getDefaultSharedPreferences(context);

Editor collection = db.edit();
Gson gson = new Gson();
String arrayList1 = gson.toJson(arrayList);

collection.putString(key, arrayList1);
collection.commit();

for retrieving

SharedPreferences db=PreferenceManager.getDefaultSharedPreferences(context);

Gson gson = new Gson();
String arrayListString = db.getString(key, null);  
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(arrayListString, type);
Muhammad Usman
  • 530
  • 4
  • 8
1

Try to use shared preference only if you have a relatively small collection of key-values that you'd like to save

Here's how to save List> into shared preference

serialize it using using gson or any other library of your choice

Gson gson = new Gson();
String serializedMapData = gson.toJson(mapList);
preferenceObj.edit().putString("key", mapList)

again convert it back into object using gson

String mapListString= preferenceObj.getString("key");
List<Map<String, String>> map = gson.fromJson(string, List.class);
Ziem
  • 6,579
  • 8
  • 53
  • 86
Vardaan Sharma
  • 326
  • 5
  • 11
0

Serialize your object to json String with Gson or any other, then store this String in SP. To get this object: get the String and deserialize it to your array.

grig
  • 848
  • 6
  • 15