2011-12-11 152 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()。 –

相關問題