Writing Objects members to Parcels

12,841

The correct and more OO way is make Bar implements Parcelable too.

To read Bar in your private Foo constructor:

private Foo(final Parcel in) {
  ... ...
  bar = in.readParcelable(getClass().getClassLoader());
  ... ...
}

To write Bar in your writeToParcel method:

public void writeToParcel(final Parcel dest, final int flags) {
  ... ...
  dest.writeParcelable(bar, flags);
  ... ...
}

Hope this helps.

Share:
12,841
tacos_tacos_tacos
Author by

tacos_tacos_tacos

Updated on June 03, 2022

Comments

  • tacos_tacos_tacos
    tacos_tacos_tacos about 2 years

    So far I've been chugging along with Parcelable objects without issue, mainly because all of their members have been types that have writeX() methods associated with them. For example, I do:

    public String name;
    
    private Foo(final Parcel in) {
        name = in.readString(); }
    public void writeToParcel(final Parcel dest, final int flags) {
        dest.writeString(name); }
    

    But now if I have a Bar member things get a little dicey for me:

    public Bar bar;
    
    private Foo(final Parcel in) {
        bar = new Bar(); //or i could actually write some constructor for Bar, this is a demo.
        bar.memberString = in.readString();
    }
    
    public void writeToParcel(final Parcel dest, final int flags) {
        // What do I do here?
    }
    

    Am I approaching this the wrong way? What should I do in my writeToParcel to parcel member Bars?