Why is it recommended to use only the default constructor to create a Fragment?

Why is it recommended to use only the default constructor to create a Fragment?

Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Today, in this blog we will discuss an Android Interview Question.

Question: Why is it recommended to use only the default constructor to create a Fragment?

It is one of the commonly asked questions during the Android Interview.

This article was originally published at Outcome School.

Let’s discuss the answer.

So, Whenever the Android Framework decides to recreate our Fragment for example in case of orientation changes. Android calls the no-argument constructor of our Fragment.

The reason why can’t it call the constructor with the argument is that Android Framework has no idea what constructor we have created. So it can’t.

Let’s look at the recommended way of creating the newInstance of Fragment:

Here is the code:

private const val EXTRA_PDF_ID = "EXTRA_PDF_ID"

fun newInstance(pdfID: Long): PdfFragment {
    val fragment = PdfFragment()
    val bundle = Bundle()
    bundle.putLong(EXTRA_PDF_ID, pdfID)
    fragment.arguments = bundle
    return fragment
}

Here this setArguments method is very important.

 fragment.arguments = bundle

We must notice that we are passing the Bundle inside it. So when we create the instance for the first time using this newInstance method. The Android Framework can extract the bundle and store it.

So, when in case of Orientation changes, the Android Framework recreates the new fragment using the no-argument constructor and can attach the bundle to the fragment as it has stored the bundle earlier.

And later again, we can access that data in our onCreate() method by using getArguments() like this.

val pdfID = arguments?.getLong(EXTRA_PDF_ID)

It means that when the system restores a fragment, it will automatically restore our bundle. And we will be able to restore the state of the fragment to the same state the fragment was initialized with.

So, now we know the answer to Why is it recommended to use only the default constructor to create a Fragment?

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

Co-Founder @ Outcome School

You can connect with me on:

Read all of our blogs here.