Write a sub class of Parcelable to another Parcel

user4o01 picture user4o01 · Sep 2, 2012 · Viewed 35k times · Source

I have a class that implements Parcelable interface:

class A implements Parcelable {

}

I have another class B that contains an A object as an instance variable. In the writeToPacel inside class B, I want to write object B to the Parcel:

class B implements Parcelable{

    public void writeToParcel(Parcel dest, int flags) {
        dest.write ??? 
    }
}

How can I write and read it?

Answer

confucius picture confucius · Sep 2, 2012
class B implements Parcelable{
//lets assume you have A as a data member 

A obj;
public void writeToParcel(Parcel dest, int flags) {

        dest.writeParcelable(obj , flags);

    }
}

if you want to read it use this

 obj = in.readParcelable(A.class.getClassLoader());