Yozh
Yozh

Reputation: 33

How to use onSaveInstanceState method with Arraylist

I have built an ArrayList with an API results. I don`t want it to disappear when a user rotates his phone.

What should I do with onSaveInstanceState?

JSONObject json = new JSONObject(result);

                    JSONArray searchArray = json.getJSONArray("Search");

                    for (int i = 0; i < searchArray.length(); i++) {
                        JSONObject searchObject = searchArray.getJSONObject(i);
                        String title = searchObject.getString("Title");
                        String type = searchObject.getString("Type");
                        String year = searchObject.getString("Year");
                        String imdbID = searchObject.getString("imdbID");

                        movieList.add(new Movie(title, type, year, imdbID));

Upvotes: 3

Views: 8726

Answers (1)

Samrat Dutta
Samrat Dutta

Reputation: 1737

Assuming the arrayList you want to keep track of is called myArrayList This code in the activity will serve your purpose :

For String Array :

ArrayList myArrayList;

//put value of myArrayList in some other method

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList("myArrayList", myArrayList);
}


protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    myArrayList = savedInstanceState.getStringArrayList("myArrayList");
}

For Custom Object Array :

Make the objects' class implement the interface Parcelable and then add the objects to the ArrayList. In your case, make the Movie class implement Parcelable and add the objects to movieList.

Then use the same methods and instead of putStringArrayList() use :

outState.putParcelableArrayList("movieList", movieList);

Similarly, use :

movieList = (ArrayList<Movie>) savedInstanceState.getParcelableArrayList("movieList");

in the onRestoreInstanceState() method to get the array back.

Upvotes: 10

Related Questions