Android DTT #9 — Generate Parcelable Boilerplate Automatically

We should focus on things that matters

Ahmad Fadli Basyari
AndroidPub
2 min readMay 9, 2017

--

Bundle is very commonly used to pass data between activities or other parts in our application. We can pass an object to a Bundle but it requires the object to be either Serializable or Parcelable.

Everyone know that, although easier to implement, Serializable is 10 times slower than Parcelable. Just doing a quick google search will gives you the impression of how slow a Serializable is.

Note: Pavel Lahoda mentioned that this not always the case in the comment. Be sure to check that out.

The thing with Parcelable is, to implement that, there are many boilerplate that we should create. This is an example of a simple class with two fields, implementing Parcelable:

That’s a lot of boilerplate just for a class with two fields.

Android Studio Default Implementation

Fortunately, Android Studio provides a way to generate those codes by adding Parcelable as one of the interface then press Option + Enter and choose Add Parcelable Implementation.

There’s a catch with this approach. If you add/remove the fields in Data class, then you need to reapply again so that the generated code will match.

Nobody ain’t got time for that.

Generated Code

Other options is to generate the boilerplate automatically. We can do this by creating an Annotation Processor to every class we want to add Parcelable implementation on it. This may very challenging task to do but we don’t have to reinvent the wheel.

There are plenty of libraries that we can use to get the job done. AutoParcel or AutoValueParcel that utilizes Google’s AutoValue, Parceler, and many others.

I personally used Parceler. It only requires us to add @Parcel to the class it will automatically creates the boilerplate code. Later, when adding the class to a Bundle we can do put and get it like this:

Bundle bundle = new Bundle();
bundle.putParcelable("data", Parcels.wrap(data));
Data data = Parcels.unWrap(bundle.getParcelableExtra("data");

Since the code is generated at compile time, everytime we add new fields to the class will be reflected when we build the apps.

Now that’s one less thing to worry about.

If you like this, hit that heart button and recommend it to your friends.

ADTT (Android Development Tips and Tricks) is a 31 series of blog posts that I’m trying to finish in throughout May. Click here for index.

--

--