Store ArrayList<CustomClass> into SharedPreferences

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

You can also store the array as a global application value.

You have to create a a class with your arraylist as the attribute like this:

public class MyApplication extends Application {

    private ArrayList<Task> someVariable;

    public ArrayList<Task> getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(ArrayList<Task> someVariable) {
        this.someVariable = someVariable;
    }
}

and you have to declare this class in your manifest file like this:

<application android:name="MyApplication" android:icon="@drawable/icon" android:label="@string/app_name">

To set and get your array you need to use:

((MyApplication) this.getApplication()).setSomeVariable(tasks);

tasks = ((MyApplication) this.getApplication()).getSomeVariable();

The above suggestions about shared preferences should also work.

Hope this helps.