Search code examples
javaandroidparcelable

ClassCastException when intercept Parcelable with inheritance


I am working in Android Studio and any time I need Parcelable just auto generate the code. My scenario is that i have super class A and class B extended from class A. I'd like to pass through an intent class B but when I intercept it I get an error sayng Caused by: java.lang.ClassCastException: pack.A cannot be cast to pack.B. The code is:

public class A implements Parcelable {

    private String str1;

    protected A(Parcel in) {
        str1 = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(str1);
    }

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

    public static final Creator<A> CREATOR = new Creator<A>() {
        @Override
        public A createFromParcel(Parcel in) {
            return new A(in);
        }

        @Override
        public A[] newArray(int size) {
            return new A[size];
        }
    };
}

public class B extends A {

    private String str2;

    protected B(Parcel in) {
        super(in);
    }
}

I'm confused about this error. Any help is apreciated


Solution

  • Consider the following scenario(using the same classes, a is super, b is child):

    You can do:

    A a = new B();
    

    But you cannot do:

    B b = new A();
    

    When you load the parcelable for B, but the type is A, you basically do this(in different code, but what you basically tell the machine is):

    B b = new A()
    

    Meaning you cannot do this as you intend per now. YOu have to create a custom creator for B, where you create a parcelable with type B.

    As for the error, it is because the creator is of type A, but you cast it to B. Which is the same as B b = new A(). So in order to resolve it you have to create a creator for B.


    Inheritance is a somewhat complicated topic, as there is a lot to keep track of in terms of what can be cast where.