Android Parcelable – The best way to passing data between activities

Android Parcelable is a serialization mechanism provided by Android to pass complex data from one activity to another activity.In order to write an object to a Parcel, that object should implement the interface “Parcelable“.

In this post, we will see how to implement a Parcelable object in an Android application to pass complex data from one activity to another activity.
To make an object Parcelable we have to implement two methods defined in Parcelable interface:

Methods of Parcelable interface

describeContents()
writeToParcel(Parcel dest, int flags)

We have to provide Parcelable. A creator that is used to create an instance of the class from the Parcel data.

Let get into the example program for Parcelable.
Consider the same class User with user details

public class User{

private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

To make this user class as Parcelable, We need to implement the Parcelable interface.Then we should override the describeContents() and writeToParcel(Parcel dest, int flags) methods.

writeToParcel
Writetoparcel method we simply write all the class attributes.

Parcel.Creator
And in the Parcel. Creator, we read the parcel data.


Android ConstraintLayout Example

Create Reusable Alert Dialog in Android


User.Java

Now the User object is ready to pass from one activity to another activity.I am going to pass this User object from my MainActivity to UserActivity using the Intent.

In my another activity I am receiving the Parcel from the Intent,


Swipe card view Android with Example[Updated]

Expandable Recyclerview For Android


 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top