Willy
Willy

Reputation: 10648

Parcelable object casting error in Android

I have a class that implements 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
    ...
}

In a point in my app, from an activity "A" I need to pass a custom object array list to another activity "B" so I do:

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

...

intent.putParcelableArrayListExtra("products", productList);

From activity "B" I get the intent:

    ArrayList<Product> productList;

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

I am performing a cast by compilation process throws error:

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

so What am I doing wrong?

Instead, if I remove the cast it compiles correctly... so I am not sure if removing the cast, once launched it will throw a runtime exception when trying to do the implicit cast.

Upvotes: 0

Views: 2941

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134664

Two problems here:

1) Your CREATOR is not generic. You have:

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

and it should be:

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

2) After that change, you don't need to manually cast it:

productList = intent.getParcelableArrayListExtra("products");

Upvotes: 2

Related Questions