0

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

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
Choletski
  • 7,074
  • 6
  • 43
  • 64

2 Answers2

1

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
1

As @njzk2 said, you need to declare a new CREATOR in class B:

public class B extends A {

    private String str2;

    protected B(Parcel in) {
        super(in);
        str2 = in.readString();
    }

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

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

        @Override
        public B[] newArray(int size) {
            return new B[size];
        }
    };
}
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87