Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store ArrayList<CustomClass> into SharedPreferences

I have an ArrayList of custom class Task

public class Task {

    String name,desc;
    Date date;
    Context context;

    public Task(String name, String desc, Date date, Context context) {
        this.name = name;
        this.desc = desc;
        this.date = date;
        this.context = context;

    }
}

I want to save it in SharedPreferences.. I read that can be done by converting it to Set.. But I don't know how to do this..

Is there a way to do this? Or any other way to store data rather than SharedPreferences?

Thanks :)

EDIT:

String s = prefs.getString("tasks", null);

    if (tasks.size() == 0 && s != null) {
        tasks = new Gson().fromJson(s, listOfObjects);
        Toast.makeText(MainActivity.this, "Got Tasks: " + tasks, Toast.LENGTH_LONG)
                .show();
    }

protected void onPause() {
    super.onPause();
    Editor editPrefs = prefs.edit();
    Gson gson = new Gson();
    String s = null;
    if(tasks.size() > 0) {
        s = gson.toJson(tasks, Task.class);
        Toast.makeText(MainActivity.this, "Tasks: " + s, Toast.LENGTH_LONG)
                .show();
    }
    editPrefs.putString("tasks", s);
    editPrefs.commit();
like image 917
Muhammad Ashraf Avatar asked Dec 15 '14 11:12

Muhammad Ashraf


1 Answers

Store whole ArrayList of Custom Objects as it is to SharedPreferences

We cannot store ArrayList or any other Objects directly to SharedPrefrences.

There is a workaround for the same. We can use GSON library for the same.

Download From Here

Using this library we can convert the object to JSON String and then store it in SharedPrefrences and then later on retrieve the JSON String and convert it back to Object.

However if you want to save the ArrayList of Custom Class then you will have to do something like the following,

Define the type

Type listOfObjects = new TypeToken<List<CUSTOM_CLASS>>(){}.getType();

Then convert it to String and save to Shared Preferences

String strObject = gson.toJson(list, listOfObjects); // Here list is your List<CUSTOM_CLASS> object
SharedPreferences  myPrefs = getSharedPreferences(YOUR_PREFS_NAME, Context.MODE_PRIVATE);
Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("MyList", strObject);
prefsEditor.commit();

Retrieve String and convert it back to Object

String json = myPrefs.getString("MyList", "");
List<CUSTOM_CLASS> list2 = gson.fromJson(json, listOfObjects);
like image 134
gprathour Avatar answered Sep 28 '22 08:09

gprathour