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.

Update: How to use the newly instantiated Fragment in your activity?
fragment_container could be any layout in your activities main layout xml. It will attach Fragment’s layout on this container layout.
UPDATE 2: DEMONSTRATING HOW TO INSTANTIATE FRAGMENT IN FRAGMENT PAGER ADAPTER

You can find the example project on https://github.com/gunhansancar/FragmentPagerExample