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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With