获取NullPointerException:尝试在Android中读取字节数组时尝试在Parcelable中获取空数组的长度

时间:2015-01-25 11:26:06

标签: android parcelable

我有一个实现Parcelable的类。我的所有值都通过writeToParcel方法设置为ok,但是当在构造函数中读取时,我遇到了一个抛出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;
    }
}

所以我注意到字节数组在读取之前没有初始化,然后我通过这种方式修改构造函数来初始化它:

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

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

现在我又得到了另一个错误:

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

那么我做错了什么?

无论如何,我不明白为什么我必须在读取时初始化字节数组,因为首先调用writeToParcel并为字节数组赋值,所以在读取时我只想从构造函数中获取WriteToParcel写的值...有人可以解释一下这个吗,拜托?也许我根本不理解Parcelable对象......

已解决:

写作......

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

阅读......

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

0 个答案:

没有答案