I am working with Parcelables in Android and I was curious about this error...

11-23 16:17:07.174: E/AndroidRuntime(1277): Caused by: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.gleason.apahelper.model.PlayerTeam

Of course this is because I am missing this...

public static final Parcelable.Creator<Player> CREATOR = new Parcelable.Creator<Player>() {
    public Player createFromParcel(Parcel in) {
      return new Player(in);
    public Player[] newArray(int size) {
      return new Player[size];

My question is, when I look at the code here I can't tell how it makes sure you have the CREATOR object. I can see where is requires the interface but I don't see where it requires the CREATOR name. Can someone explain this a little better? I would like to use this pattern in other code I am writing so I was wondering if someone could explain it.


That is implemented in the Parcel class in the method public final <T extends Parcelable> Parcelable.Creator<T> readParcelableCreator(). If it can't get the creator from a specified class loader, it assumes the default 'CREATOR' one:

    Parcelable.Creator<T> creator;
    synchronized (mCreators) {
        HashMap<String,Parcelable.Creator> map = mCreators.get(loader);
        if (map == null) {
            map = new HashMap<String,Parcelable.Creator>();
            mCreators.put(loader, map);
        creator = map.get(name);
        if (creator == null) {
            try {
                Class c = loader == null ?
                    Class.forName(name) : Class.forName(name, true, loader);
                Field f = c.getField("CREATOR");
                creator = (Parcelable.Creator)f.get(null);

Edit: Forgot to mention that the method makes use of reflection to get a field implemented in a class using c.getField("CREATOR").


Just thought I'd give an update as to the error message you are seeing.

Here's the bit responsible for that, still all handled by reflection nonetheless.

public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
                Field f = parcelableClass.getField("CREATOR");
                if ((f.getModifiers() & Modifier.STATIC) == 0) {
                    throw new BadParcelableException("Parcelable protocol requires "
                            + "the CREATOR object to be static on class " + name);

Your Answer

