Difference between Parcelable and Serializable?

by admin

In order to develop an Android App, we all learn that we cannot just pass object references to activities and fragments, we have to put those in an Intent / Bundle.

Passing primitive data types like string, integer, float, etc. through intents is quite easy in Android. All you have to do is put the data with unique key in intents and send it to another activity. If a user wants to send Java objects through intent, Java class should be implemented using the Parcelable interface. Serialization, on the other hand, is a Java interface that allows users to implement the interface which gets marked as Serializable.

public class User {
String UserName;
String Reg;

public User(String name,String reg){
UserName=name;
Reg=reg;

}
}

Above is the simple User class with three private fields and getters and setters.
Here we can not pass objects of this class between activities/services. To do this we need to make this class parcelable or serializable.
Here taking an example of Parcable

public class User implements Parcelable{

String UserName;
String Reg;
public User(String name,String reg ){
UserName=name;
Reg=reg;
}

//parceling part
public User(Parcel in){
String[] data= new String[2];

in.readStringArray(data);
this.UserName= data[0];
this.Reg= data[1];
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub

dest.writeStringArray(new String[]{this.UserName,this.Reg});
}

public static final Parcelable.Creator CREATOR= new Parcelable.Creator() {

@Override
public User createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new User(source); //using parcelable constructor
}

@Override
public User[] newArray(int size) {
// TODO Auto-generated method stub
return new User[size];
}
};

}

1 thought on “Difference between Parcelable and Serializable?

Sanjeev Krishna Thakur Ji August 22, 2017 at 9:27 am

I believe this site has very good written subject matter content .

Reply

Leave a Reply

Your email address will not be published.
*
*