Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Array List Object in SharedPreferences

Tags:

This method add new object into ArrayList

//get text from textview time = date.getText().toString(); entry_d = entry.getText().toString(); dayName = day.getText().toString();  arrayList.add( new ArrayObject( dayName, entry_d ,time)); 

I am trying to add these 3 strings in SharedPrefrences. Here is my code:

private void savePreferences(String key, String value) {      SharedPreferences sharedPreferences = PreferenceManager                                                   .getDefaultSharedPreferences(this);     Editor editor = sharedPreferences.edit();     editor.putBoolean(key, value);     editor.commit(); } 

This method only add one string at a time where as I want to add 3 strings in one go. Is there any method I can implement.

like image 999
usrNotFound Avatar asked Apr 10 '14 09:04

usrNotFound


People also ask

Can I save array list in SharedPreferences?

You can save String and custom array list using Gson library. =>First you need to create function to save array list to SharedPreferences. public void saveListInLocal(ArrayList<String> list, String key) { SharedPreferences prefs = getSharedPreferences("AppName", Context. MODE_PRIVATE); SharedPreferences.


1 Answers

Convert your array or object to Json with Gson library and store your data as String in json format.

Save;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sharedPrefs.edit(); Gson gson = new Gson();  String json = gson.toJson(arrayList);  editor.putString(TAG, json); editor.commit(); 

Read;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); Gson gson = new Gson(); String json = sharedPrefs.getString(TAG, ""); Type type = new TypeToken<List<ArrayObject>>() {}.getType(); List<ArrayObject> arrayList = gson.fromJson(json, type); 
like image 62
Sinan Kozak Avatar answered Sep 20 '22 17:09

Sinan Kozak