Getting NullPointerException: trying to get the length of a null array in Parcelable when trying to read an array of bytes in Android

I have a class that implements Parcelable. All my values ​​are set normally using the writeToParcel method, but when reading inside the constructor, I have a problem with a byte array that throws a NullPointerException:

public final class Product implements Parcelable { private Integer ID; private byte[] image; // Constructors public Product(){} public Product(Parcel source) { this.ID = source.readInt(); source.readByteArray(this.image); } public int describeContents() { return this.hashCode(); } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.ID); dest.writeByteArray(this.image); } public static final Parcelable.Creator<Product> CREATOR = new Parcelable.Creator<Product>() { public Product createFromParcel(Parcel in) { return new Product(in); } public Product[] newArray(int size) { return new Product[size]; } }; // Getters public Integer getID () { return this.ID; } public byte[] getImage() { return this.image; } // Setters public void setID (Integer id) { this.ID = id; } public void setImage(byte[] image) { this.image = image; } } 

therefore, I noticed that before reading it, the byte array is not initialized, and then initialize it, modifying the constructor as follows:

  public Product(Parcel source) { this.ID = source.readInt(); this.image = new byte[source.readInt()]; source.readByteArray(this.image); } 

and now I get the following error:

 Caused by: java.lang.NullPointerException: Attempt to get length of null array 

So what am I doing wrong?

Anyway, I don’t understand why I should initialize the byte array when reading, since writeToParcel is called first and assigns a value to the byte array, so when reading I want to get the value written by WriteToParcel from the constructor ... Can someone explain this to me , you are welcome? Maybe I don’t understand Parcelable object at all ...

DECISION:

In recording...

  dest.writeInt(this.image.length); dest.writeByteArray(this.image); 

In read ...

  this.image = new byte[source.readInt()]; source.readByteArray(this.image); 
+6
source share

Source: https://habr.com/ru/post/981511/


All Articles