Java – NullPointerException when trying to read parcel ArrayList
I have a class message that implements Parcelable It contains an ArrayList, and attachmentsdata is also one of my classes When I try to pass messageobject from my mainactivity to another activity, I get NullPointerException when I try to read this ArrayList
Error:
In "public void writetoparcel (parcel DeST, int flags)", when I write ArrayList:
dest.writeTypedList(attachments);
In "private void readfromparcel (parcel in)", it seems that the error is caused by:
in.readTypedList(attachments,AttachmentsData.CREATOR);
I've tried to find different ways to solve the problem and tried some versions, one of which is:
in.readList(attachments,AttachmentsData.class.getClassLoader());
But the application crashed Does anyone know what I did wrong? In other words, I obviously write or read ArrayList in an incorrect way, but what is the correct method?
Thank you, Christina
Editor, I may have just solved it. I changed it to
attachments = in.createTypedArrayList(AttachmentsData.CREATOR);
Seems to work! I guess it might have the same effect as David Wasser's answer?
Solution
Before calling readtypedlist(), you need to set the attachments variable to a list, as shown below:
attachments = new ArrayList<AttachmentsData>();