Android Parcelable - Write and read ArrayList< IA > when IA is a interface

Pedro Bernardo picture Pedro Bernardo · Mar 21, 2013 · Viewed 27.6k times · Source

I have a interface IA and class B and C that implement them. Both B and C implement Parcelable as well.

Then I have the tricky part:

Class D has a ArrayList< IA >. I need this too insert both classes B and C in the arraylist. They share the same structure but the "IS-A" relation don't apply.

I need to pass D from one activity to another as a Parcel.

I've tried to write (ArrayList<IA>) in.readSerializable but I got a IOException. I know that if IA was not a interface the problem was easy, but I can't seem to find an easy solution for this.

Any ideas?

@SuppressWarnings("unchecked")
public D (Parcel in) {
    list = new ArrayList<IA>();
    (...)    
    list = (ArrayList<IA>) in.readSerializable 
    }

@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
    public D createFromParcel(Parcel in) {
        return new D(in);
    }

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

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
    (...)
    dest.writeList(list);
}

Answer

Pedro Bernardo picture Pedro Bernardo · Dec 10, 2013
    @SuppressWarnings("unchecked")
public D (Parcel in) {
    list = new ArrayList<IA>();
    (...)    
    //ERROR -> list = (ArrayList<IA>) in.readSerializable 
    list = in.readArrayList(IA.class.getClassLoader());
}

@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
    public D createFromParcel(Parcel in) {
        return new D(in);
    }

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

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
    (...)
    dest.writeList(list);
}