Android Tutorial 4 – Passing Custom Objects between Activities

Its simple enough to place basic variables into an intent and retrieve it on the other end but what about custom objects.  It is actually quite simple as well.

In The Class Definition

public class Obj implements Parcelable

Make sure your class definition for the object implements Parcelable.

Then add the following functions to the class:

public static final Parcelable.Creator<Obj> CREATOR = new Parcelable.Creator<Obj>() {
    public donObj createFromParcel(Parcel in) {
        return new Obj(in);

    public Obj[] newArray(int size) {
        return new Obj[size];

public int describeContents() {
   return 0;

Take the above as face value write it in as seen replacing Obj with the name of the class.

public void writeToParcel(Parcel dest, int flags) {     

Every variable you wish to obtain on the other end, in the loading activity,  you need to include a line in the above function in the format of: dest.write<data type>(VarName);. The order you write the variable in is the order it then comes out in the following function.

public Obj(Parcel in) {
   Var1= in.readString();
   Var2= in.readString();
   Var3= in.readDouble();

If you do not follow the same order you used in the writeToParcel function the data will get scrambled and potentially your app will crash due to a data type mismatch.

In the Activity

To add the object to an intent as an extra:

Intent.putExtra("CustObj", VarObj);

To retrieve it:

parcelObj = getIntent().getExtras().getParcelable("CustObj")

Or something along those lines with getParcelable on the end depending on how you like to retrieve the extras.


So that is that you can now freely pass your custom objects between Activities as simply as you do any other simple data types.  I hope you found this tutorial useful leave me your comments and feedback.


If you dont mind download my android game from the Play Store and give me your thoughts on that too: Ball Pop Drop


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s