Best Practice to Instantiate Fragments with Arguments in Android

There are some ways to instantiate and pass data to fragments in android development. However, you must be careful when you do that and you should avoid the wrong approaches while you are instantiating and passing data to fragments.

The most recommended way of instantiate fragments with arguments is to have factory methods for this task.

Also, another important topic is about how to pass data to the fragments while instantiating them. In this case it is tempting to directly access the fields of your fragment and assign their values. However, this is the wrong approach. Because when your application send back to background and the other applications require more and more memory then your application and its resources will be cleared from the memory to open up space to the new ones.

In this example, to instantiate MyFragment you need to call;

Fragment fragment = MyFragment.newInstance("Gunhan", 28);

If android decides to recreate your activity and fragment, it is going to call no-argument constructor and the system guarantees to pass the arguments bundle to it.

After that when you want to return to your application the android system will create your activity and also your fragment with the default constructor with the passed arguments bundle.

Therefore if you directly set your fields then you are gonna lose their values after recreate operation.

 

  • Luke Allison

    Just wondering in what situation one would need to add this to the manifest: android:configChanges=”orientation|keyboardHidden|screenSize” . I had someone help me write an application and they felt the need to override the orientation handling but it has broken all other fragments in the app.

  • Ragtime Ragtime

    It returns Name: null and Age: 0

    • Hi Ragtime,

      Do you mind to share your code sample maybe you are missing a point.

      • Ragtime Ragtime

        I used your code, nothing different :/

        • Are you sure that you are using exactly the same for instance you should instantiate the fragment ‘Fragment fragment = MyFragment.newInstance(“Gunhan”, 28);’ this way. not like new MyFragment(). This piece of code is 100% working so you should identify what you are missing or send me a sample code so that I can find your missing piece.