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

  1. November 5, 2011 at 8:41 pm

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

  1. No trackbacks yet.

Leave a comment