Search code examples
androidparcelableparcel

How to parcel two object which are in a bidirectional one-to-one relationship?


I have two object like these that I want to send through Intent implementing Parcelable interface:

class Foo implements Parcelable
{
    private Bar bar;

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

class Bar implements Parcelable
{
    private Foo foo;

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

How can I implement correctly the Parcelable interface?


Solution

  • I would do it this way:

    In writeToParcel of Foo class write all fields of Foo instance without Bar field and all fields of Bar instance without Foo field.

    Then in Foo(Parcel in) read all fields of Foo and use fields of Bar to create the Bar instance and link both objects together.