Home > Tricks & Tips > Pass complex object structure to Intent

Pass complex object structure to Intent


Intent class supports developers to put several primitive type, however, sometimes we need to pass complex data structure to it. It’s ok to use Serialize, but due to performance, it is kind of not really good.

There is another way around it is to implement data structure to Parcelable interface, in which we need to implement two methods:

	@Override
	public int describeContents() {

	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {

	}

1. describeContents(): describe the kinds of special objects contained in this Parcelable’s marshalled representation.
2. writeToParcel(): flatten this object in to a Parcel.

Also, we need to implement a static field: Parcelable.Creator<T> CREATOR, which will generate the object of class will be implemented.

Check out from Android Developers’ Guide Reference on Parcelable interface

This is a sample:

package pete.android.study;

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

public class SongInfo implements Parcelable {
	private String mTitle;
	private String mSinger;

	public SongInfo(String title, String singer) {
		mTitle = title;
		mSinger = singer;
	}

	public SongInfo(Parcel in) {
		String[] data = new String[2];
		in.readStringArray(data);
		mTitle = data[0];
		mSinger = data[1];
	}

	public void setTitle(String title) {
		mTitle = title;
	}
	public String getTitle() {
		return mTitle;
	}

	public void setSinger(String singer) {
		mSinger = singer;
	}
	public String getSinger() {
		return mSinger;
	}

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

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeStringArray(new String[] {
				mTitle,
				mSinger
		});
	}

	public static final Parcelable.Creator<SongInfo>CREATOR = new Parcelable.Creator<SongInfo>() {

		@Override
		public SongInfo createFromParcel(Parcel source) {
			return new SongInfo(source);
		}

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

	};
}

Now you can put it into an Intent for passing:

data.putExtra("SongInfo", new SongInfo("Happy New Year", "ABBA"));

Or even put an ArrayList

data.putParcelableArrayListExtra("SongList", mListPlaying);

Hope you like it!

Cheers,
Pete Houston

About these ads
  1. November 5, 2011 at 8:41 pm | #1

    Thanks.. putting two strings together as an array.. was confused for a while.. thanks a lot.. :)

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: