Gursimran Bedi
Gursimran Bedi

Reputation: 117

Saving arraylist as SharedPreferences

I have a recyclerview with many elements that I want to save with SharedPreferences for when my app is closed and reopened. The code for my array is below.

public ArrayList<MyInformation> getDataSet() {
        ArrayList results = new ArrayList<MyInformation>();    
        return results;
    }

(I add stuff to the recyclerview with this in myAdapter)

public void addEntity(int i, MyInformation entity) {
        information.add(i, entity);
        notifyItemInserted(i);
    }

So, how would I save this array for when I close the app? Thanks!

Upvotes: 0

Views: 2265

Answers (1)

Gunhan
Gunhan

Reputation: 7035

You can save your list of data in sharedpreferences as String by using Gson. Before doing that of course you need to add neccesarry dependencies

dependencies {
    compile 'com.google.code.gson:gson:2.3.1'
}

Then when you want to save, convert your array into String:

ArrayList<MyInformation> yourData = new ArrayList<MyInformation>();
String dataStr = new Gson().toJson(yourData);

To retrieve and convert back to an object is also simple:

String str = "";//you need to retrieve this string from shared preferences.

Type type = new TypeToken<ArrayList<MyInformation>>() { }.getType();
ArrayList<MyInformation> restoreData = new Gson().fromJson(str, type);

There you have it

Upvotes: 4

Related Questions