Problem in implementing Parcelable containing other Parcelable

前端 未结 2 565
不思量自难忘°
不思量自难忘° 2020-12-31 22:21

I\'m implementing Parcelable class that has another Parcelable insde.

In OuterParcelable class:

@Override
public void writeToParcel(Parcel dest, int          


        
2条回答
  •  离开以前
    2020-12-31 22:45

    Why are you putting the value into a Bundle? Did you completely implement the parcelable in your class?

    Parcelable Skeleton

    public MyClass(Parcel in) {
        readFromParcel(in);
    }
    
        //
    // Parcelable Implementation
    @Override
    public int describeContents() {
        return 0;
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) { 
        dest.writeParcelable(aParcelableClass, flags);
    }
    
    private void writeObject(Parcel dest, Object obj) {
        if (obj != null) {
            dest.writeInt(1);
            dest.writeValue(obj);
        } else {
            dest.writeInt(0);
        }
    }
    
    public void readFromParcel(Parcel in) {
        aParcelableClass = in.readParcelable(ParcelableClass.class.getClassLoader());
    }
    
    private Object readObject(Parcel in) {
        Object value = null;
    
        if (in.readInt() == 1) {
            value = in.readValue(null); // default classloader
        }
    
        return value;
    }
    
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        @Override
        public MyClass createFromParcel(Parcel source) {
            return new MyClass(source);
        }
    
        @Override
        public MyClass[] newArray(int size) {
            return new MyClass[size];
        }
    };
    

    I added a few things to make null values more easily dealt with, but the principle is the same. You need the @Override items, constructor, and Creator.

    If you're going to read and write a parcelable you will have issues if you specify null as the class loader.

提交回复
热议问题