Serializable
, Parcelable
is a data type that we usually pass through Intent
or Bundle
when switching to another Activity
or Fragment
. This is an interface for classes whose instances can be written to and restored from a Parcel
. Parcelable
process is much faster than Serializable
(a standard interface in JDK). One of the reasons for this is that we are being explicit about the serialization process instead of using reflection to infer it. It also stands to reason that the code has been heavily optimized for this purpose.Classes implementing the
Parcelable
interface must also have a non-null static field called CREATOR
of a type that implements the Parcelable.Creator
interface. More over, there are some methods you must override:
describeContents()
: describe the kinds of special objects contained in thisParcelable
's marshalled representation. Return a bitmask indicating the set of special object types marshalled by theParcelable
.writeToParcel()
: flatten this object in to aParcel
.- A constructor with
Parcel
as the parameter: read all class variables fromParcel
.
Serializable
, by making a class which implements Parcelable
we must write a lot of boring/similar codes (especially your class has so many private variables). So, as a lazy developer like me, you would think to use a generating tool. In this tip, I will present a powerful plugin on IntelliJ/Android Studio to make this work more comfortable and quickly.
Installing the plugin
Step 2: In Android Studio, select menu File -> Settings... (on Windows) or File -> Preferences... (on MacOS), select Plugin entry on the left-side pane. You will have this dialog:
Step 3: Click at "Install plugin from disk" and select the download jar file:
Step 4: Click "OK", the dialog will be closed and the plugin has installed. This dialog will appear and click "Restart" to restart Android Studio:
Usages in your class
And you will have this result:
Customer.java
Now, your work has been done without typing lengthy codes! For more details, please go to the plugin page on Github and read it's documentation! Moreover, check these reference links to understanding package info.devexchanges.parcelableplugin;
import android.os.Parcel;
import android.os.Parcelable;
public class Customer implements Parcelable {
private String name;
private int id;
public Customer(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.id);
}
protected Customer(Parcel in) {
this.name = in.readString();
this.id = in.readInt();
}
public static final Creator CREATOR = new Creator() {
@Override
public Customer createFromParcel(Parcel source) {
return new Customer(source);
}
@Override
public Customer[] newArray(int size) {
return new Customer[size];
}
};
}
Parcelable
in Android:
- Google guide and example
- Parcelable.java source code.