将List作为ParcelableArrayList传递 [英] Passing a List through as a ParcelableArrayList

查看:1895
本文介绍了将List作为ParcelableArrayList传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,伙计们,我在使用某些代码时遇到了麻烦。我正在实施parcelables。基本上我有一个全球发起的项目列表

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<>();

我希望将其传递为parcellable以在旋转时保存实例状态。我实现了saveOnInstanceState方法和onCreate

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);
    }
}

唯一的问题是它会引发错误并且错误点到outstate.putParcelableArrayList行。

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

有没有人知道修复或解决此问题的方法?我尝试使用谷歌搜索并查看其他stackoverflow答案,但无法找到一个有效。

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.

如果有人想要查看整个项目,那么这是项目的GitHub链接,上面提到的方法尚未提交。
https://github.com/Rykuno/Flix-Viewer

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

推荐答案

可悲的是Android并没有编程到界面。如果 List 不是 ArrayList ,那么你别无选择,只能创建一个新的的ArrayList 。这不是什么大问题,可以通过编程方式完成。

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);
}

这篇关于将List作为ParcelableArrayList传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆