Rykuno
Rykuno

Reputation: 468

Passing a List through as a ParcelableArrayList

So hey guys, Im having some trouble with some code. Im implementing parcelables. Basically I have an List of items initiated globally as

private List<Movie> mMovieList = new ArrayList<>();

and I wish to pass this in as a parcellable to save the instance state upon rotation. I implement the saveOnInstanceState method and onCreate

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList(MOVIE_KEY, (ArrayList< ? extends Parcelable >)mMovieList);
}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (savedInstanceState != null)
    {
        mMovieList = (List<Movie>)savedInstanceState.get(MOVIE_KEY);
    }
}

Only problem is it throws an error and the error points to the outstate.putParcelableArrayList line.

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Does anyone know of a fix or a way around this? I tried googling and looking at other stackoverflow answers but couldnt find one that worked.

Here is the GitHub link to the project if anyone wants to look at its entirety, the methods mention above have not been committed yet. https://github.com/Rykuno/Flix-Viewer

Upvotes: 0

Views: 90

Answers (1)

Steve Kuo
Steve Kuo

Reputation: 63094

Sadly Android doesn't "program to the interface". If the List is not an ArrayList then you'll have no choice but to create a new ArrayList. This isn't a big deal and can be done programmatically.

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    ArrayList<Movie> toSave = mMovieList instanceof ArrayList ?
        (ArrayList<Movie>)mMovieList : new ArrayList<Movie>(mMovieList);
    outState.putParcelableArrayList(MOVIE_KEY, toSave);
}

Upvotes: 1

Related Questions