创建parcelable的正确方法是什么?

时间:2015-07-11 13:48:08

标签: android android-fragments bundle parcelable

我创建了以下parcelable对象:

public class ViewModel implements Parcelable {

private String image, price, credit, title, description, id;

public ViewModel(String image, String price, String credit, String title, String description, String id) {
    this.image = image;
    this.price = price;
    this.credit = credit;
    this.title = title;
    this.description = description;
    this.id = id;
}

public String getPrice() {
    return price;
}

public String getCredit() {
    return credit;
}

public String getDescription() {
    return description;
}

public String getId() {
    return id;
}

public String getTitle() {
    return title;
}

public String getImage() {
    return image;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeStringArray(new String[] {
            this.image,
            this.price,
            this.credit,
            this.title,
            this.description,
            this.id
    });
}

/** Static field used to regenerate object, individually or as arrays */
public static final Parcelable.Creator<ViewModel> CREATOR = new Parcelable.Creator<ViewModel>() {
    public ViewModel createFromParcel(Parcel pc) {
        return new ViewModel(pc);
    }
    public ViewModel[] newArray(int size) {
        return new ViewModel[size];
    }
};

/**Creator from Parcel, reads back fields IN THE ORDER they were written */
public ViewModel(Parcel pc){
    image = pc.readString();
    price = pc.readString();
    credit = pc.readString();
    title = pc.readString();
    description = pc.readString();
    id = pc.readString();
}

}

现在我通过捆绑包发送ArrayList ViewModel

 bundle.putParcelableArrayList("products", viewModels);

我在做什么事吗?因为我获得了null Bundle Arguments,但是如果我发送一个简单的字符串,一切都会正常工作。

2 个答案:

答案 0 :(得分:0)

进行此更改:

charAt(int)

答案 1 :(得分:0)

您正在尝试检索可分割的ArrayList。您需要检索您创建的可分段ViewModel对象。变化:

bundle.putParcelableArrayList("product", viewModels);

getIntent().getParcelableArrayList("product");

到:

bundle.putParcelable("product", viewModels);

getIntent().getParcelable("product");