Serializable vs Parcelable in Android
Hello! Developers, Today I am going to discuss about what is Serializable and Parcelable, and when we use this concept and why.
Serializable
Serializable is a standard Java interface which belongs to java.io.Serializable. It is not part of the Android SDK. It is easy to use due to its simplicity. We have to simply implement it with the POJO class. Here is an example:-
public class Employee implements Serializable {
private String name;
private int age;
public String address;
public Employee(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
Now, we are ready to go. To pass these objects, we have to code like this:-
//we can pass data like this from activity
Employee employee = new Employee("ABC", 23, "XYZ 03");
mIntent.putExtra("EMPLOYEE_KEY", employee);//we can get data like this in other activity
getIntent().getSerializableExtra("EMPLOYEE_KEY");
Parcelable
Parcelable is also an interface that belongs to android.os.Parcelable. It is part of the Android SDK. It converts the object into a byte stream and passes the data between activities. To implement this with POJO class we have to override some methods and write Creators method. Here is an example:-
public class Employee implements Parcelable {
private int age;
private String name;
private String address;
public Employee(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Employee(Parcel source) {
age = source.readInt();
name = source.readString();
address = source.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(age);
dest.writeString(name);
dest.writeString(address);
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public static final Creator<Employee> CREATOR = new Creator<Employee>() {
@Override
public Employee[] newArray(int size) {
return new Employee[size];
}
@Override
public Employee createFromParcel(Parcel source) {
return new Employee(source);
}
};
}
We can pass Parcelable objects like this:-
//we can pass data like this from activity
Employee employee = new Employee("ABC", 23, "XYZ 03");
mIntent.putExtra("EMPLOYEE_KEY", employee);
//we can get data like this in other activity
getIntent().getParcelableExtra("EMPLOYEE_KEY");
Difference between Serializable and Parcelable
- Serializable is a slow process whereas Parcelable is fast.
- Parcelable interface takes more time to implement in comparison to Serializable.
- Serializable creates lots of temporary objects in comparison to Parcelable.
- Serializable is not reflection safe whereas Parcelable is reflection safe.
I hope it was a useful article for you. I wish you healthy days!