Serializable and Parcelable are both ways to flatten your Java object in order to send them across process boundaries. Serializable comes from standard Java and is much easier to implement so, naturally that's where I started. All you need to do is implement the Serializable interface and add override two methods.
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
Simple enough however there is one small gotcha, the constructor for your object is never called so you may have to add some additional setters to handle your constructor arguments and do a little reorganization. The problem with Serializable is that it tries to appropriately handle everything under the sun and uses a lot reflection to make determine the types that are being serialized. This leads to is being painfully slow for large amount of object. By large in this case I mean tens of decently beefy objects, not hundreds or thousands.
The second method is to use Androids Parcelable interface. This is a good bit more complex as you need to use the development tools that come with the Android SDK to create the Android Inter-Process Communication (AIPC) file to tell Android how is should marshal and unmarshal your object. The upside is that it is less generic and doesn't use reflection so it should have much less overhead and be a lot faster.
There are two methods that you need to override:
public int describeContents();
public void writeToParcel(Parcel dest, int flags);
And you need to make sure that you implement a static public final Parcelable.Creator called CREATOR. Here is an example of a simple Parcelable implementation:
public class MyParcelable implements Parcelable
{
private int mData;
public void writeToParcel(Parcel out, int flags)
{
out.writeInt(mData);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator()
{
public MyParcelable createFromParcel(Parcel in)
{
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size)
{
return new MyParcelable[size];
}
}
private MyParcelable(Parcel in)
{
mData = in.readInt();
}
}