发送Parcelable对象的ArrayList时发生ClassCastException

时间:2014-01-27 00:08:55

标签: android classcastexception parcelable

尝试将用户定义的Parceleable对象的ArrayList发送到另一个活动。

在Activiy1中:
ArrayList<MyObject> uiObjects;
//Code populating the arraylist

Intent intent = new Intent(this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("objectList", uiObjects);
intent.putExtras(bundle);
startActivity(intent);

在活动2中:
Bundle bundle = getIntent().getExtras();

ArrayList<MyObject> uiObjects = bundle.getParcelableArrayList("objectList");

发生了一件我无法弄清楚的有趣事情。当我尝试迭代uiObjects时,我得到一个 ClassCastException 。 使用ADT调试器,我确保在Activity1中正确填充了“uiObjects”,并且有2个条目。 但是在Activity 2中,一个是我的对象,另一个似乎是一个Integer对象(NO IDEA FROM WHERE)。 查找了发送可分配对象的ArrayList的其他帖子,但找不到类似的问题。关于这里可能发生什么的任何见解?

2 个答案:

答案 0 :(得分:0)

您添加了太多级别 - 您的额外内容包含Bundle,其中包含您的parcelable ArrayList因此,当您致电bundle.getParcelableArrayList("objectList")时,返回的内容为Bundle ,而不是你期望的uiObjects。而是使用putParcelableArrayListExtra()

Intent intent = new Intent(this, Activity2.class);
intent.putParcelableArrayListExtra ("objectList", uiObjects); 
startActivity(intent);

答案 1 :(得分:0)

我想额外的水平是不必要的,但是,这并没有错。  正如我做的那样: 我呼叫Bundle bundle = getIntent().getExtras();之前,在Activity2中getParcelableArrayList

原来我在Parceleable方法中的writeToParcel类MyObject中有一个错误。(我放入dest.writeDouble(x)代替dest.writeInt(x)在一个地方)。修复似乎已经有效,现在它可以正常工作,而无需对上面的代码进行任何更改。

我仍然想知道实际上是什么让它产生了如此奇怪的输出(在返回的Integer中有一个正确的对象和一个ArrayList对象)。