Working with Parcelable in Android

Dear fellow coders, today I have come before you to tell you that… well, our topic is how to send Objects in android context using intent(with what else there is?) with the help of Parcelable.

Let’s begin shall we.

PreConditions, writer/I assumes you already have good understanding in the topic of Serializable(java), and/or hopefully have struggled in android with it’s perfomance,

We have a simple model class, with all the cute fields and methods that goes along with it, then suddenly you are asked to send the object’s instances around activities, or any methods that needs Parcelable object

public class Paro {   
private int id;
private String name;
private String detail;
Paro(){}
}

Here is how you Pimp ride an object to Parcelable

  1. implement Parcelable to use int describeContents() and void writeToParcel(Parcel dest, int flags) methods
  2. use a method(private constructor in our case) to assign the fields content from the Parcel Object.
public class Paro  implements Parcelable{   
//....

public Paro() {}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(name);
parcel.writeString(detail);
}
private Paro(Parcel in){
id= in.readInt();
name=in.readString();
address=in.readString();
}

Implement Parcelable.Creator<Paro> CREATOR to create the object back from Parcel Object

public static final Parcelable.Creator<Paro> CREATOR = new Parcelable.Creator<Paro>() {    
@Override
public Paro createFromParcel(Parcel in) {
return new Paro(in);
}
@Override
public Paro[] newArray(int size) {
return new Paro[size];
}
};

Now we are done with making our Paro class parcelable, and we are left with sending it and reading it back on the receiver’s side

//on Activity side
Paro parox = new Paro();
paro.seId(1);
paro.setName(“jack sparrow”);
paro.setDetail(“A savvy Pirate,Indeed”);
Intent intent = new Intent(this,ParoDetailActivity.class);
intent.putExtra("paro",parox);
startActivity(intent);

on Receiver’s Activity request the object, you don’t even need to cast

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
DocsItem mDocItem = getIntent().getParcelableExtra("paro");

One more thing, make sure the ORDER of Parceling and Deparceling(hope that’s how you say it) of the fields in the methods writeToParcel(Parcel parcel, int i) and createFromParcel(Parcel in) should be kept, or you will run into a null object.

Enjoy coding, and I will see you next time.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.