Suppose I want to store a custom object of type MyObject
in an Intent
. The way to do this is to make MyObject
implement Parcelable
. If one of the fields of MyObject
is also a custom object of type Widget
the obvious thing to do is to make Widget
implement Parcelable
too.
The trouble is that there is a huge amount of boilerplate involved when implementing Parcelable
. You can get around this by not making Widget
implement Parcelable
but instead just giving it a constructor taking a Parcel
and a method writeToParcel
as follows:
public final class Widget {
private final int a;
private final String b;
Widget(Parcel in) {
a = in.readInt();
b = in.readString();
}
void writeToParcel(Parcel out) {
out.writeInt(a);
out.writeString(b);
}
}
You can then have a Widget
field in a Parcelable
object as follows:
public class MyObject implements Parcelable {
private final int x;
private final Widget w;
MyObject(int x, Widget w) {
this.x = x;
this.w = w;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(x);
w.writeToParcel(out);
}
public static final Parcelable.Creator<MyObject> CREATOR
= new Parcelable.Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel in) {
return new MyObject(in.readInt(), new Widget(in));
}
@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
}
Is this an acceptable approach? Is it considered unidiomatic android to have many custom classes in a project that can be written to and read from Parcel
s without them actually implementing Parcelable
? Or does the fact that I am using a Parcelable
to pass complex objects with many fields of custom types (which in turn have many fields of custom type etc etc), indicate that I shouldn't be using Parcelable
in the first place?