Fast, easy Parcelable implementation with Android studio Parcelable plugin

Starting from conclusion

Use Parcelable class is always encouraged for better performance, while it is much easier to use Serializable class for fast checking/implementation.

Easy & fast implementation of Parcelable? → Use Android studio plug-in!

Serializable and Parcelable difference

Serializable & Parcelable class can be used to pass object references from one Activity to the other Activity via Intent/Bundle. Your object must implement either  Serializable or Parcelable in order to pass it via Intent.

  • Serializable, the Master of Simplicity
  • Parcelable, the Speed King

by Parcelable vs Serializable

Serializable is defined in JAVA language as  a marker interface, so after implementing Serializable no extra method implementation is needed. It is very easy to use, but the performance is not good since serializing mechanism is decided by Java and it uses refelection.

Parcelable class is provided by Android platform,  and its performance is much faster than Serializable (according to this blog, it is more than 10 times faster!!). This is because the serialization method is explicitly written in Parcelable class. It means you need to implement serialization method, following 4 methods/members, which is quite troublesome.

  • writeToParcel()
  • Constructor with argument Parcel
  • Parcelable.Creator<> CREATOR
    • createFromParcel()
    • newArray()
  • describeContents()

Binder and AIDL works with Parcelable.

Using Android studio plugin to Easily implement Parcelable class

There is a way to achieve implementing above Parcelable methods/members automatically using “IntelliJ/Android Studio Plugin for Android Parcelable boilerplate code generation” plugin.

1. Install plugin

Open Android studio → File → Settings → Plugins → Browse repositories, type “parcel” to find “Android Parcelable code generator” 

Cite from: https://guides.codepath.com/android/using-parcelable

2. How to use

1. Open class which you want to implement Parcelable, and Press [ALT+Insert] (cursor position doesn’t matter, plugin always insert automatically generated code at the bottom of class). You can select “Parcelable”.
parcelable_code_generator_1

2. Select fields to be parceled. Usually just press OK.

parcelable_code_generator_2

3. Done! below methods are automatically generated, so easy.

parcelable_code_generator_3

Refrence

Passing Serializable, Parcelable by Intent

Suppose you want to pass Movie class instance movie, from MainActivity to DetailsActivity.

Sender side: use putExtra method to contain movie object data in Intent.

Receving side: Use getSerializableExtra or getParcelableExtra method to extract data.

Reference

Sponsored Links

One response

Leave a Reply

Your email address will not be published.