2011-12-11 96 views
2

我遇到了将对象集合写入parcel的问题。我为MyObject的集合(即它实现Parcelable任何物体)内部存储MyRegistry那一定是Pacelable还有:writeParcelableArray抛出ClassCastException Android

public class MyObject implements Parcelable {...} 

public class MyRegistry implements Parcelable { 

    private List<Parcelable> mRegistry = new ArrayList<Parcelable>(); 

    ... 

    public void writeToParcel(Parcel dest, int flags) 
    { 
    dest.writeParcelableArray((Parcelable[])mRegistry.toArray(), flags); 
    } 
} 

然而,当writeParcelableArray()被称为抛出ClassCastException。那么编写Parcelable的MyObject有什么问题?在文档中没有遇到任何关于此的限制...

先谢谢您!

+0

无需将mRegistry转换为'(Parcelable [])' –

回答

2

我认为这是因为List.toArray()返回一个Object []数组,然后尝试转换。您应该改用List.toArray(T[])

+0

您绝对是对的!非常感谢!还有一件事现在还不清楚是另一方的readParcelableArray的ClassLoader参数。 Registry类不知道存储在其中的对象的实际类型,它们只是Parcelable ... –

+0

Uff,答案来自http://stackoverflow.com/questions/1996294/problem-unmarshalling-parcelables。我从我的应用程序上下文中使用ClassLoader:getContext()。getClassLoader()。 –

相关问题