Transfer Data between Fragment’s with Android Parcelable

What should you do when you want to pass an object and its data from one fragment to the other? You use the parcelableinterface. Parcelable is an Android only Interface used to serialize a class so its properties can be transferred from one activity/fragment to another.The Parcelable interface adds methods to all classes you want to be able to transfer between activities/fragment. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.

Lets understand this approach with an example. Consider a mobile application to view  associate data. Here we have two fragments – Fragment A and Fragment B. We need pass associate data from Fragment A to B, when fragment A is replaced with Fragment B.

For example, let Associate be a class to hold associate information. The class contains a series of associate data, getter functions and a constructor to create a single object of the class.

 

public class Associate implements Parcelable {
String name,empId;
public Associate(String name, String empId) {
this.name = name;
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
//constructor used for parcel
public Associate(Parcel in) {
name= in.readString();
empId= in.readString();
} 
//creator - used when un-parceling our parcle (creating the object)
 public static final Creator<Associate> CREATOR = new Creator<Associate>() {
@Override public Associate createFromParcel(Parcel in) {
return new Associate(in); } @Override public Associate[] newArray(int size) { 
return new Associate[size]; } };@Override public int describeContents() { return 0; }//write object values to parcel for storage
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name); 
dest.writeString(empId); 
}}

Next we need to pass data from fragment to another 

1) Create an object of Associate class
val associate= Associate("John","980076") 2) Replace fragment A with Fragment B. Here Associate_key is the key used to pass and receive data in different fragments. val fragmentA= FragmentA() val bundle = Bundle(); bundle.putParcelable("Associate_key",associate); fragmentA.setArguments(bundle); val transaction = fragmentManager!!.beginTransaction() transaction.replace(R.id.container, bookingFragment) transaction.commit() 3) Receive object in Fragment B
val args = arguments

if (args != null) {
    val data= args.getParcelable<Associate>("Associate_key")
//Here we can access name and empId transferred from Fragment A to B using data.name and data.empId.

}

Add a Comment

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