Android 中的 Parcelable 对象转换错误

Parcelable object casting error in Android

我有一个 class 实现了 parcelable:

public final class Product implements Parcelable {
    private Integer ID;
    private String title;

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

    public int describeContents() {
        return this.hashCode();
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.ID);
        dest.writeString(this.title);
    }

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

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

    // Getters
    ...

    // Setters
    ...
}

在我的应用程序中,从 activity "A" 我需要将自定义对象数组列表传递给另一个 activity "B" 所以我这样做:

ArrayList<Product> productList = new ArrayList<Product>();
productList.add(new Product(...))
productList.add(new Product(...))

...

intent.putParcelableArrayListExtra("products", productList);

来自 activity "B" 我明白了意图:

    ArrayList<Product> productList;

    Intent intent = this.getIntent();
    productList = (ArrayList<Product>) intent.getParcelableArrayListExtra("products");

我正在通过编译过程抛出错误执行强制转换:

Error:(38, 78) error: inconvertible types
required: ArrayList<Product>
found:    ArrayList<Parcelable>

所以我做错了什么?

相反,如果我删除强制转换它会正确编译...所以我不确定是否删除强制转换,一旦启动它会在尝试进行隐式强制转换时抛出运行时异常。

这里有两个问题:

1) 您的 CREATOR 不是通用的。你有:

public static final Parcelable.Creator CREATOR
        = new Parcelable.Creator() {

应该是:

public static final Parcelable.Creator<Product> CREATOR
        = new Parcelable.Creator<Product>() {

2) 改完之后就不用手动投了:

productList = intent.getParcelableArrayListExtra("products");