What is Parcelable in android
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
During my Android course, the instructor used this block of code and they didn't quite explained this. How can I interpret this code? I tried reading the documentation but I failed to interpret.
This concept is called Parcelable
A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.
To allow your custom object to be parsed to another component they need to implement the android.os.Parcelable interface. It must also provide a static final method called CREATOR which must implement the Parcelable.Creator interface.
The code you have written will be your model class.
You can use Parcelable in Activity like :
intent.putExtra("student", new Student("1")); //size which you are storing
And to get this object :
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
Here Student is a model class name. replace this with yours.
In simple terms Parcelable is used to send a whole object of a model class to another page.
In your code this is in the model and it is storing int value size to Parcelable object to send and retrieve in other activity.
Reference :
Tutorial 1
Tutorial 2
Tutorial 3