It can be solved using gson(https://github.com/google/gson). Simply add compile files ('libs/gson-2.2.4.jar')
on your gradle dependencies section.
Suppose you are using Arraylist of
class YOUR_CLASS
for listview. ie
private ArrayList<YOUR_CLASS> arraylist = new ArrayList<YOUR_CLASS>();
Now after adding item objects to your arraylist
you can save it in Shared preference using:
SharedPreferences preferences = getSharedPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String arraylist_in_string = gson.toJson(arraylist).toString(); //Converting it to String
editor.putString("YOUR_KEY", arraylist_in_string); //now saving the String
editor.commit();
Now when you need to use the arraylist
you can take it from sharedPreferences using
Gson gson = new Gson();
String arraylist_in_string = preferences.getString("YOUR_KEY", null);
if(arraylist_in_string != null) //if we have list saved
{
//creating a list of YOUR_CLASS from the string response
Type type = new TypeToken<ArrayList<YOUR_CLASS>>() {}.getType();
List<YOUR_CLASS> list = new Gson().fromJson(arraylist_in_string, type);
//now adding the list to your arraylist
if (list != null && list.size() > 0 )) {
arraylist.clear();// before clearing check if its not null.
arraylist.addAll(list);
}else //ie list isn't saved yet
{
//You may want to save the arraylist into Shared preference using previous method
}