Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Objects members to Parcels

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?

like image 262
tacos_tacos_tacos Avatar asked Mar 28 '12 20:03

tacos_tacos_tacos


People also ask

How do you write an object to a parcel?

Note that the values should be read from the Parcel in the same order they are written into it using writeToParcel. To write an Arraylist of Objects into parcel, you can use parcel. writeList(objectName); To read the ArrayList, use parcel.

How do you make Parcelable?

Create Parcelable class without plugin in Android Studioimplements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

What is Androidos parcel?

A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.

Why do we use Parcelable in Android?

Parcelable and Bundle objects are intended to be used across process boundaries such as with IPC/Binder transactions, between activities with intents, and to store transient state across configuration changes.


1 Answers

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.

like image 100
yorkw Avatar answered Oct 05 '22 22:10

yorkw