Prashant Ruinfotech
Prashant Ruinfotech

Reputation: 23

how to store ArrayList<HashMap<String, String>> data into sharedpreferences?

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

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

Upvotes: 2

Views: 2952

Answers (3)

Muhammad Usman
Muhammad Usman

Reputation: 530

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);

Upvotes: 6

Vardaan Sharma
Vardaan Sharma

Reputation: 336

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);

Upvotes: 1

grig
grig

Reputation: 847

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.

Upvotes: 0

Related Questions