实现包含List的Parcelable接口的对象会抛出NullPointerException

Lal*_*ani 3 android parcelable

我正在尝试List使用该Parcelable接口创建一个包含对象的对象.我无法读Parcel回来的对象.

谁能指出我正确的方向?我在这里错过了什么?

MyParcelable 宾语:

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];
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

MyListClass 宾语:

  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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Oct*_*ean 16

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

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

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

public MyParcelable(Parcel in) {
    myInt = in.readInt();
    arrList = new ArrayList<MyListClass>();
    in.readTypedList(arrList, MyListClass.CREATOR);
}
Run Code Online (Sandbox Code Playgroud)