9

I have a class that implements the Parcelable. All my values are set ok through the writeToParcel method but when reading within the constructor I have a problem with a byte array that throws 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;
    }
}

so I have noticed that byte array is not initialized before reading it and then I initialize it by modifying the constructor in this way:

    public Product(Parcel source) {
        this.ID = source.readInt();

        this.image = new byte[source.readInt()];
        source.readByteArray(this.image);
    }

and now I get this another error:

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

So what am I doing wrong?

Anyway, I do not understand why I have to initialize the byte array when reading as writeToParcel is called first and assign a value to byte array so when reading I only want to get the value written by WriteToParcel from the constructor... Could someone explain me this as well, please? Maybe I am not understanding Parcelable object at all...

SOLVED BY:

In write...

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

In read...

    this.image = new byte[source.readInt()];
    source.readByteArray(this.image);
Willy
  • 9,848
  • 22
  • 141
  • 284
  • 3
    I already have solved it, see updated post. I do not delete the issue because I want to share it so it can help some other people. – Willy Jan 25 '15 at 11:39

0 Answers0