Home > Software engineering >  Why occured Exception: Fragment not attached to a context
Why occured Exception: Fragment not attached to a context

Time:01-27

I create Fragment named HomeFragment.

And write code that show DialogFragment in Fragment(HomeFragment) below

private fun showCustomDialog() {
    CustomDialog().apply {
        arguments = Bundle().apply {
            putString("title", requireContext().getString(R.string.app_name))
        }
    }.show(parentFragmentManager, "customDialog")
}

When I used requireContext() to get title in Bundle().apply, Exception occured like below

Fragment CustomDialog{1ef2304} (4ca006b2-19b7-4550-a227-e5c6d1d43e02) not attached to a context.

On the other hand, Exception not occured when I used this@HomeFragment instead of using requireContext()

private fun showCustomDialog() {
    CustomDialog().apply {
        arguments = Bundle().apply {
            // Exception not occured
            putString("title", [email protected](R.string.app_name))
        }
    }.show(parentFragmentManager, "customDialog")
}

using requireContext() is that context is null, Why?

CodePudding user response:

Because your CustomDialog is a Fragment and requireContext() resolves to your CustomDialog instead of the containing HomeFragment due to the apply scope function. After instantiating the dialog fragment it is not yet attached to any context, so requireContext() will throw.

  • Related