There are many examples of how to implement parcelable. Here is the canonical one. Here is an answer from SO.
Basically, you implement a method public void writeToParcel(Parcel out, int flags)
where you write all the fields you want persisted into the out
value.
Then implement an anonymous implementation of a Parcelable.Creator
parameterized with your parcelable class. This anonymous implementation must be named CREATOR
.
Finally, make a private constructor like this: private MyParcelable(Parcel in)
. Where you read all the values you wrote in the out
back into the fields of your object in the in
.
Then you need to make Detail parcelable too! Oh joy!
It needs to look like this:
public class MasterWithDetails implements Parcelable {
private String value;
private List<Detail> detailList;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(value);
out.writeString(getName());
out.writeTypedList(detailList); //don't forget to make Detail parcelable too!
}
public static final Parcelable.Creator<MasterWithDetails> CREATOR
= new Parcelable.Creator<MasterWithDetails>() {
public MasterWithDetails createFromParcel(Parcel in) {
return new MasterWithDetails(in);
}
public MasterWithDetails[] newArray(int size) {
return new MasterWithDetails[size];
}
};
private MasterWithDetails(Parcel in) {
value = in.readString();
setName(in.readString());
detailList = in.createTypedArrayList(Detail.CREATOR);
}
}