Android – an object that implements the Parcelable interface containing a list throws a NullPointerException
•
Android
I'm trying to create an object with a list of objects that can be. I can't read the parcel object back
Who can point me in the right direction? What did I miss 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);
}
}
resolvent:
The problem is that when the creator of the myparcelable object calls the private constructor of the parcel from which the object is reconstructed, the ArrayList is still uninitialized and therefore null
Now, the method calls readtypedlist () to try to write the parcels content to the ArrayList you specified, which throws nullpointereception because it has not been initialized
The solution is to initialize ArrayList before calling this method
public MyParcelable(Parcel in) {
myInt = in.readInt();
arrList = new ArrayList<MyListClass>();
in.readTypedList(arrList, MyListClass.CREATOR);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码