我有一个实现 Parcelable 的类。我的所有值都通过 writeToParcel 方法设置正常,但在构造函数中读取时,我遇到了引发 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);
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)