Parcelable inheritance: abstract class - Which CREATOR?

心已入冬 提交于 2019-12-05 03:35:53
Albert Llorens Mestre

I used Vincent Mimoun-Prat's parcelable architecture from this post: Parcelable and inheritance in Android and ran into the same typed list problem about having to specify an impossible abstract CREATOR.

Searching in Parcel's JavaDoc I found the method writeList(List val) that internally uses writeValue(Object) method for each object of the list and therefore calling writeToParcel() from subclasses (B and C from an A list). To unmarshall the list use its counterpart readList (List outVal, ClassLoader loader) where A ClassLoader has to be passed or an android.os.BadParcelableException is thrown, at least in my case.

Class containing A elements list should be something like this:

public class AContainer implements Parcelable {
    //Other AContainer fields
    List<A> elements = new ArrayList<>();
    //Other AContainer fields

    static final Parcelable.Creator<AContainer> CREATOR = new Parcelable.Creator<AContainer>() {
        @Override
        public AContainer createFromParcel(Parcel source) {
            return new AContainer(source);
        }

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

    public AContainer() {
    }

    protected AContainer(Parcel source) {
        //read other AContainer fields
        source.readList(elements, A.class.getClassLoader());
        //read other AContainer fields
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //write other AContainer fields
        dest.writeList(elements);
        //write other AContainer fields
    }
}

Using these methods may be a bit slower than readTypedList() and writeTypedList() but specific data from B and C subclasses is also "parcelled" and not only the fields from A abstract superclass (It will be impossible being abstract). You recover the right instances from B and C.

public class A implements Parcelable{

       public A(){

       }

       public A(Parcel in){
            super(in);
           // read from parcel
           // number = in.readInt() etc
       }

       @Оverride
       public int describeContents(){
           return 0;
       }

       @Override
       public void writeToParcel(Parcel dest, int flags) {
           super.writeToParcel(out, flags);
          // write to parcel
          // out.writeInt
       }
       public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
           public Student createFromParcel(Parcel in) {
               return new A(in); 
           }

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

B and C must also implement Parcelable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!