Starting from conclusion
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
Parcelable class can be used to pass object references from one Activity to the other Activity via Intent/Bundle. Your object must implement either
Parcelable in order to pass it via Intent.
- Serializable, the Master of Simplicity
- Parcelable, the Speed King
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.
- Constructor with argument
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”
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”.
2. Select fields to be parceled. Usually just press OK.
3. Done! below methods are automatically generated, so easy.
- Using Parcelable (It contains nice gif demonstrate animation)
- Quickly Create Parcelable Class in Android Studio
Passing Serializable, Parcelable by Intent
Suppose you want to pass
Movie class instance
Sender side: use
putExtra method to contain
movie object data in
Intent intent = new Intent(this, DetailsActivity.class); intent.putExtra(DetailsActivity.MOVIE, movie);
Receving side: Use
getParcelableExtra method to extract data.
private static final String MOVIE = "Movie"; // key mSelectedMovie = (Movie)this.getIntent().getSerializableExtra(MOVIE); // Serializable mSelectedMovie = getActivity().getIntent().getParcelableExtra(MOVIE); // Parcelable