Posted on

Android Bundle, Parcelable, Parcel


android bundle

Let’s look at Android Bundle class and how it works. It has a pretty easy api, but how does it actually work under the hood?

Bundle

We use Android Bundle class implicitly when passing data between activities through Intent with methods like Intent#putExtra. This method delegates it to related Bundle method: Bundle#putString/putByte etc.

Also we use Bundle when restoring activity state in Activity#onSaveInstanceState/onRestoreInstanceState and you get it in onCreate as parameter as well

And Bundle stores this data in a simple ArrayMap with key values, but that’s not where the magic happens

Parcelable

You’re probably familiar with Parceleble class, we use for marshalling/unmarshalling as a more efficient replacement for Serializable. Most common use case is when you want to pass your own class to different activity. Then you need to implement some of it’s framework methods

And Bundle itself is Parcelable, it implements it as well.

Parcel

When you have your Parcelable implementation you deal with Parcel class. The first thing about this class to understand is how write/read methods work

Basically it’s data stored sequentially in order of its insertions, like a list. And you can access any by moving a cursor.

Here’s an example of Parcel class, you can play around with it by moving methods order and see what happens. After writing/reading new data cursor moves to the next position, so you need to reset it to start with Parcel#setDataPosition method

All methods are native in C++ so if you want to find implementation – you need to look at GitHub/googlecode repo

And if you use read methods in the wrong order of writing it will mess things up, so you always need to read types in the exact same order as you wrote them

As you see all the core stuff of Bundle is in Parcel class and to understand how it works you need to go through the source code

Source Code

I love digging into the source code and see how stuff was actually written. Most of those api’s are in C++ so you’ll have to go through this repo

Luckily there’s an amazing GitHub in repo search up there, so you can find stuff pretty easy! Here’s Parcel code stuff in C++

You don’t need to understand any of that code, the only important thing is – reading data from parcel in exact same order of writing it.

 

Thanks for reading, don’t forget to subscribe!


  • Andres Garcia

    Parcelable are great but writing them is a pain in the butt.
    Luckily for us, many Android Studio plugins can transform a simple POJO into a Parcelable with just one right click…
    Also, for those using Firebase, you can only send Firebase Object across Android components (to avoid extra calls) if Parcelable. Won’t work with Serializable !!