I have two kinds of custom objects Movie
and DetailedMovie
which are stored into an ArrayList<Object>
. After doing a network operation my ArrayList
is populated exclusively with either objects of type Movie
or of type DetailedMovie
. I am using a list of type object because they are linked to an adapter and the adapter then sorts out the views depending on what type of object is in the list.
So, the problem is that I want to store the contents of the ArrayList into a Bundle in onSaveInstanceState. Both my Movie and DetailedMovie objects implement Parcelable, but when I try
List<Object> mObjectMovieList = new ArrayList<>();
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(MOVIE_LIST_KEY, mObjectMovieList);
}
I am told
Wrong 2nd argument type. Found: 'java.util.List<java.lang.Object>', required: 'java.util.ArrayList<? extends android.os.Parcelable>'
How can I get around this?
The reason being for this is that Object
class do not extend Parcelable
.
1st Option
One of the solution that I can suggest here is to make a parent class that extends Parcelable
and then both Movie
and DetailedMovie
extend that class.
So, it would look like:
List<MovieWrapper> mObjectMovieList = new ArrayList<>();
where MovieWrapper
is parent of Movie
and DetailedMovie
class Movie extends MovieWrapper
class DetailedMovie extends MovieWrapper
2nd Option
The other option is to filter the array into specific type and then call putParcelableArrayList
ArrayList<Movie> movieList = mObjectMovieList.stream().filter(p->p instanceOf Movie).collect(Collectors.toCollection(ArrayList::new));
ArrayList<DetailedMovieList> detailedMovieList = mObjectMovieList.stream().filter(p->p instanceOf DetailedMovieList).collect(Collectors.toCollection(ArrayList::new));
outState.putParcelableArrayList(MOVIE_LIST_KEY, movieList);
outState.putParcelableArrayList(DETAILED_MOVIE_LIST_KEY, detailedMovieList);
You may need to amend the above code as it is just a suggestion and can be changed as required.