Share Object between Fragments

Sometimes you need to share your custom objects between several fragments. You can achieve this several ways.

But I explain here via Serialize object. Lets Starts. Thanks @dory & @aamir khan From Smart Developers Lab for their support to write this one.

I have a Class Division which Implements Serializable from java.io.Serializable. It has a field called name & its corresponding setter getter method.
 import java.io.Serializable;  
   
 @SuppressWarnings("serial")  
 public class Division implements Serializable{  
   
      private String name;  
   
      public String getName() {  
           return name;  
      }  
   
      public void setName(String name) {  
           this.name = name;  
      }  
   
 }  

I am transfer the object Division object from HomeFragment to OfficeCategoryFragment.

Now in HomeFragment


 android.support.v4.app.FragmentTransaction ft = getActivity()  
        .getSupportFragmentManager().beginTransaction();  
      ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
      OfficeCategoryFragment frag = new OfficeCategoryFragment();  
   
      Bundle bundles = new Bundle();  
   
       
      Division aDivision = divisionList.get(position);  
   
      // ensure your object has not null  
        
      if (aDivision != null) {  
         
       bundles.putSerializable("aDivision", aDivision);  
       Log.e("aDivision", "is valid");  
   
      } else {  
       Log.e("aDivision", "is null");  
   
      }  
      frag.setArguments(bundles);  
      ft.replace(android.R.id.content, frag);  
      ft.addToBackStack(null);  
      ft.commit();  

Get the Object in OfficeCategoryFragment :

 Bundle bundle = getArguments();  
     
 Division division= (Division) bundle.getSerializable("aDivision");  

Now you can use your Custom Object.