我具有以下類讀取和寫入對象的數組從/到一個包裹:讀取&Parcelable的書寫陣列對象
class ClassABC extends Parcelable {
MyClass[] mObjList;
private void readFromParcel(Parcel in) {
mObjList = (MyClass[]) in.readParcelableArray(
com.myApp.MyClass.class.getClassLoader()));
}
public void writeToParcel(Parcel out, int arg1) {
out.writeParcelableArray(mObjList, 0);
}
private ClassABC(Parcel in) {
readFromParcel(in);
}
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<ClassABC> CREATOR =
new Parcelable.Creator<ClassABC>() {
public ClassABC createFromParcel(Parcel in) {
return new ClassABC(in);
}
public ClassABC[] newArray(int size) {
return new ClassABC[size];
}
};
}
在上面的代碼中,我得到一個ClassCastException
讀取readParcelableArray
時:
錯誤/ AndroidRuntime(5880):引起:java.lang.ClassCastException:[Landroid.os.Parcelable;
上述代碼有什麼問題?在寫對象數組時,我應該先將數組轉換爲ArrayList
?
UPDATE:
是否確定對象數組轉換爲ArrayList
並添加它來包裹?例如,書寫時:
ArrayList<MyClass> tmpArrya = new ArrayList<MyClass>(mObjList.length);
for (int loopIndex=0;loopIndex != mObjList.length;loopIndex++) {
tmpArrya.add(mObjList[loopIndex]);
}
out.writeArray(tmpArrya.toArray());
讀取時:
final ArrayList<MyClass> tmpList =
in.readArrayList(com.myApp.MyClass.class.getClassLoader());
mObjList= new MyClass[tmpList.size()];
for (int loopIndex=0;loopIndex != tmpList.size();loopIndex++) {
mObjList[loopIndex] = tmpList.get(loopIndex);
}
但現在我得到了NullPointerException
。以上方法是否正確?爲什麼它會拋出NPE?
mConversationMemberList的類型是什麼? – Chetan 2012-04-09 10:08:42
我已經更新了這個問題,它是MyClass []類型的。 – User7723337 2012-04-09 10:14:45