Daily Archives: October 28, 2009

Writing Parcelable classes for Android

I’ve just released version 0.3 of Xydroid, my small Xymon monitoring app. It should now be a bit more suited to Android 2.0, and have just a couple fewer bugs in it.

As it turns out, the main problem with running under Android 2.0 for my app was de-parceling of a Parcelable representation of the XML files used by Xydroid. Up until now, I had just written out all the data in the tree when parceling, and read until no data was left when de-parceling. As it turns out, if this parcelable class is put into a bundle with other data, such as strings or integers, the de-parceling code will just continue reading along the bundle. The error I tended to encounter would be “Unmarshalling unknown type code 6946932” (or some other number), presumably as I tried to read a String from where an integer existed or similar.

The solution seems to be to write how much data you are planning to parcel as the first bit of information, and only read back this many chunks before passing control back. This works both in 2.0 and 1.5/1.6, whereas reading until there was no more data seemed to work in 1.5/1.6 but not 2.0 — though this might just have been pure luck.

Update: I thought I had better actually show how I ended up implementing my Parcelable classes, so here is a quick example of how to wrap a HashMap in something parcelable:
Continue reading