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>() {
    @Override
    public donObj createFromParcel(Parcel in) {
        return new Obj(in);
    }

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

@Override
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) {     
   dest.writeString(Var1);
   dest.writeString(Var2);
   dest.writeDouble(Var3);
}

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 comment