Thursday, December 23, 2010

Parcelable interface in android

The most efficient way to pass custom objects between android activities in by implementing the Parcelable interface. Two methods describeContents and writeToParcel needs to be overridden


public class MyParcel implements Parcelable{
private String name;
private List emails;

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int arg1) {
dest.writeString(name);

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("emails", emails);
dest.writeBundle(bundle);

}
}

In this example MyParcel class has a name and a list of emails which we would like write to a parcel so that other activities can have access to it. As you can see the basic java types have their corresponding write methods to write a user defined class or a list we first create a bundle and then write it to the parcel.

No comments: