12

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?

tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126

2 Answers2

30

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.

yorkw
  • 40,926
  • 10
  • 117
  • 130
  • 5
    adding because some might get confuse here **getClass().getClassLoader()** means **Bar.class.getClassLoader()** – Junaid Oct 12 '16 at 17:22
  • What should I do if my class is provided by the SDK and cannot be modified? – Eido95 Nov 15 '16 at 20:10
0

Parceables are a pain and only pass by value and not reference. I would never recommend using them. Make a static model instance if you application and just get a shim reference to the object you need.

user123321
  • 12,593
  • 11
  • 52
  • 63
  • Using singletons as a design principle is flawed in object oriented programming. Deserialize into json or store the values, do not have a global class all your other classes can access. – HarshMarshmallow Jul 13 '16 at 17:05