Obtendo NullPointerException: tentativa de obter o comprimento da matriz nula no Parcelable ao tentar ler uma matriz de bytes no Android
Eu tenho uma classe que implementa o Parcelable. Todos os meus valores são definidos ok através do método writeToParcel, mas ao ler dentro do construtor, tenho um problema com uma matriz de bytes que gera 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;
}
}
então notei que a matriz de bytes não é inicializada antes de lê-la e, então, inicializo modificando o construtor da seguinte maneira:
public Product(Parcel source) {
this.ID = source.readInt();
this.image = new byte[source.readInt()];
source.readByteArray(this.image);
}
e agora eu recebo esse outro erro:
Caused by: java.lang.NullPointerException: Attempt to get length of null array
Então, o que estou fazendo de errado?
De qualquer forma, eu não entendo por que tenho que inicializar a matriz de bytes ao ler como writeToParcel é chamado primeiro e atribuir um valor à matriz de bytes. Ao ler, só quero obter o valor gravado por WriteToParcel do construtor ... Alguém poderia explicar me isso também, por favor? Talvez eu não esteja entendendo o objeto Parcelable ...
RESOLVIDO POR:
Na gravação ...
dest.writeInt(this.image.length);
dest.writeByteArray(this.image);
Na leitura ...
this.image = new byte[source.readInt()];
source.readByteArray(this.image);