Skip to content Skip to sidebar Skip to footer

Parcelable Inheritance Issue With Getcreator Of Heir Class

I have a parcelable class A and B that extends A Example: The class A public abstract class A implements Parcelable { private int a; protected A(int a) { this.a =

Solution 1:

Here is how I implemented this. I created an abstract parent class, lets use your parent class A, where you should add two abstract methods: protected abstract void writeChildParcel(Parcel pc, int flags) and protected abstract void readFromParcel(Parcel pc)

Then you need a static method to create the right instance of A. In my case it made sense to have a type attribute (you can use an enum) where I could identify each of them. This way we can have a static newInstance(int type) method like so:

publicstatic A newInstance(int type) {
    A a = null;
    switch (type) {
    caseTYPE_B:
            a = newB();
            break;
        ...
    }
    return a;
 }

publicstatic A newInstance(Parcel pc) {
    A a = A.newInstance(pc.readInt()); ////call other read methods for your abstract class here
    a.readFromParcel(pc);
    return a;
 }

publicstatic final Parcelable.Creator<A> CREATOR = newParcelable.Creator<A>() {
    public A createFromParcel(Parcel pc) {
        return A.newInstance(pc);
    }
    public A[] newArray(int size) {
        returnnew A[size];
    }
};

Then, write your writeToParcel as follows:

publicvoidwriteToParcel(Parcel out, int flags) {
    out.writeInt(type);
    //call other write methods for your abstract class here
    writeChildParcel(pc, flags);
}

Now get rid of your CREATOR and all other Parcelable methods in B and just implement writeChildParcel and readFromParcel in it. You should be good to go!

Hope it helps.

Post a Comment for "Parcelable Inheritance Issue With Getcreator Of Heir Class"