Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Passing objects through intents?

I know how intents are used to pass primitive values to another activity. How would i pass a "custom class" object, lets say Person class, to another activity.

1 Answer

Using the recommended method of Parcelable:

import android.os.Parcel;
import android.os.Parcelable;


public class Person implements Parcelable {
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    // Parcelable Interface --------

    // Creates the copy in the new Activity
    public static final Creator<Person> CREATOR =
        new Creator<Person>() {
            public Person createFromParcel(Parcel in) {
                return new Person(in);
            }

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

    // Used by CREATOR
    private Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    // Mind the read and write order. They
    // need to stay the same between this
    // method and the private constructor
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(firstName);
        dest.writeString(lastName);
    }
}

Now you can pass in Person just like any other extra.

You can also implement Serializable instead, though it's not as optimized.