Getting NullPointerException: Attempt to get length of null array in Parcelable when trying to read a byte array in Android

淺唱寂寞╮ 提交于 2019-12-05 18:35:24

问题


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);

来源:https://stackoverflow.com/questions/28135819/getting-nullpointerexception-attempt-to-get-length-of-null-array-in-parcelable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!