3

I am trying to make an object containing a List of objects parcelable using the Parcelable interface. I am not able to read the Parcel object back in.

Can anyone point me in the right direction? What am I missing here?

MyParcelable object:

public class MyParcelable implements Parcelable {

    private int myInt = 0;
    private List<MyListClass> arrList;

    public List<MyListClass> getArrList() {
        return arrList;
    }

    public void setArrList(List<MyListClass> arrList) {
        this.arrList = arrList;
    }

    public int getMyInt() {
        return myInt;
    }

    public void setMyInt(int myInt) {
        this.myInt = myInt;
    }

    MyParcelable() {
        // initialization
        arrList = new ArrayList<MyListClass>();
    }

    public MyParcelable(Parcel in) {
        myInt = in.readInt();
        in.readTypedList(arrList, MyListClass.CREATOR);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel outParcel, int flags) {
        outParcel.writeInt(myInt);
        outParcel.writeTypedList(arrList);
    }

    public static final Parcelable.Creator<MyParcelable> CREATOR =
            new Parcelable.Creator<MyParcelable>() {

        @Override
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        @Override
        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };
}

MyListClass object:

  public class MyListClass implements Parcelable{

    private int test;

    public MyListClass()
    {}

    public MyListClass(Parcel read){
        test = read.readInt();
    }

    public int getTest() {
        return test;
    }

    public void setTest(int test) {
        this.test = test;
    }

    public static final Parcelable.Creator<MyListClass> CREATOR = 
        new Parcelable.Creator<MyListClass>() {

            @Override
            public MyListClass createFromParcel(Parcel source) {
                return new MyListClass(source);
            }

            @Override
            public MyListClass[] newArray(int size) {
                return new MyListClass[size];
            }
        };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel arg0, int arg1) {
        arg0.writeInt(test);
    }
}
4

2 回答 2

16

问题是,当您的MyParcelable对象的创建者调用私有构造函数时,Parcel您从中重建对象,ArrayList因此仍然未初始化null

现在方法调用readTypedList()尝试将Parcels 内容写入ArrayList您指定的引发 a的内容,NullPointerEception因为它尚未初始化。

ArrayList解决方案是在调用该方法之前初始化。

public MyParcelable(Parcel in) {
    myInt = in.readInt();
    arrList = new ArrayList<MyListClass>();
    in.readTypedList(arrList, MyListClass.CREATOR);
}
于 2011-08-11T11:46:04.687 回答
1

in.readTypedList(arrList, MyListClass.CREATOR);

调用时此时的 arrList 尚未初始化return new MyParcelable(in);

于 2011-08-11T11:47:13.947 回答