创建包含字节数组的自定义Parcelable对象

4

我正在尝试创建一个包含字节数组的Parcelable类。我已经尝试了各种方法,但是如果我想将Parcelable放入我的意图中,它似乎仍然会失败。

public class Car implements Parcelable{

private String numberPlate;
private String objectId;
private byte[] photo;
private String type;
private ParseGeoPoint location;
private ParseUser owner;
private String brand;
private double pricePerHour;
private double pricePerKm;
public static final String TYPES[] = {"Cabrio", "Van", "SUV", "Station", "Sedan", "City", "Different"};


public Car(String numberPlate, byte[] bs, String type, ParseGeoPoint location, String brand) {

    this.numberPlate = numberPlate;
    this.photo = bs;
    this.type = type;
    this.brand = brand;
    this.setLocation(location);
    this.owner = ParseUser.getCurrentUser();
}

public Car(Parcel in){
    readFromParcel(in);
}

 public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public Car createFromParcel(Parcel in) {
            return new Car(in);
        }

        public Car[] newArray(int size) {
            return new Car[size];
        }
    };



public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(type);
    dest.writeString(numberPlate);
    dest.writeString(brand);
    dest.writeDouble(pricePerHour);
    dest.writeDouble(pricePerKm);
    dest.writeString(objectId);
    dest.writeByteArray(photo);


}

public void readFromParcel(Parcel in){
    this.type = in.readString();
    this.numberPlate = in.readString();
    this.brand = in.readString();
    this.pricePerHour = in.readDouble();
    this.pricePerKm = in.readDouble();
    this.objectId = in.readString();
    byte[] ba = in.createByteArray();
    in.unmarshall(ba, 0, ba.length);
    this.photo = ba;

}

如果我不包含字节数组,它可以正常运行。


阅读以下内容 http://prasanta-paul.blogspot.in/2010/06/android-parcelable-example.html#comment-form - Akram
1个回答

12

你为什么要使用createByteArray?我修改了你的代码,应该可以正常工作了...

public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(type);
    dest.writeString(numberPlate);
    dest.writeString(brand);
    dest.writeDouble(pricePerHour);
    dest.writeDouble(pricePerKm);
    dest.writeString(objectId);
    dest.writeInt(photo.length());
    dest.writeByteArray(photo);
}



public void readFromParcel(Parcel in){
    this.type = in.readString();
    this.numberPlate = in.readString();
    this.brand = in.readString();
    this.pricePerHour = in.readDouble();
    this.pricePerKm = in.readDouble();
    this.objectId = in.readString();
    this.photo = new byte[in.readInt()];
    in.readByteArray(this.photo);
}

https://dev59.com/B2gt5IYBdhLWcg3w7ByL - Akshat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接