- To pass primitive data types like string, integer, float, we use intents which is very direct.Add key name and the respective data type value in the Intents but for class objects,then we need to use Serialization or Parcelable.
- For marshalling and unmarshalling of java objects,Parcelable and Serialization are used.Java serialization or Anroid parcelable(pass object references between activities)
- Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements. It is a marker interface as it converts an object into a stream using the Java reflection API.
- In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API and this helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects during the stream conversation process.Due to this, the Serialization process is slow in comparison to Parcelable.
- Serialization, on the other hand, is a Java interface that allows users to implement the interface which gets marked as Serializable.
- Android developers prefer Parcelable over Serialization technique as Serialization is available in Java.
Parcelable:
- Parcelable is faster than Serialization makes it a preferred choice of approach while passing an object because Android Parcelable implementation allows objects to read and write from Parcels which can contain flattened data inside message containers.We can write custom code for marshaling and unmarshaling so it creates fewer garbage objects using Parcelable. The performance of Parcelable over Serialization dramatically improves (around two times faster), because of this custom implementation.
- If a developer wants to convert a Java object into Parcelable, then the best way to do so is by implementing the Parcelable interface and overriding the writeToParcel() methods in its own class.
- The first step is to override the writeToParcel() method and write all object members into parcel objects.
- The second is to create a static Parcelable.Creator object to de-serialize the Java object. Parcelable is well documented in the Android SDK;
- In Parcelable, One of the main reasons was the fact that Parcelable is fully customizable, allowing developers to convert required data into Parcelable.
- Parcelable examples:
protected void onCreate(Bundle savedIntanceState){
super.onCreate(savedInstanceState);
}
2) MyClass myClassObj=new MyClass();
Intent myIntent=new Intent();
myIntent.putExtra("myClassObj",myClassObj);