将列表作为 ParcelableArrayList 传递 [英] Passing a List through as a 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<>();
并且我希望将其作为可分块传递以在旋转时保存实例状态.我实现了 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);
}
这篇关于将列表作为 ParcelableArrayList 传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!