How to fix not attached to an activity in Android

In my application I want use this library for ImagePicker :

But after add this line private val imagePicker: ImagePicker = registerImagePicker(this) show me Force close.

I want use this into Fragment and this fragment info ViewPager2 .
FragmentAdapter code :

class FragmentsAdapter (fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int {
        return 2

    override fun createFragment(position: Int): Fragment {
        when (position) {
            0 -> return FragmentA()
        return FragmentB()

FragmentB codes :

class FragmentB : Fragment(), ImagePickerResultListener {

private val imagePicker: ImagePicker = registerImagePicker(this)


    private fun openImagePicker() {


Error message :

java.lang.IllegalStateException: Fragment MandatoryInfoFragment{ccb6b52} (d0165abf-9555-41a8-a139-d84da8774350) not attached to an activity.
    at com.myapp.ui.login.pages.complete.mandatory.MandatoryInfoFragment.<init>(FragmentB.kt:51)
    at com.myapp.ui.login.pages.complete.FragmentsAdapter.createFragment(FragmentsAdapter.kt:22)

How can I fix it?

>Solution :

The reason is registerImagePicker is calling requireActivity() to get the Context . And at the time of initialization requireActivity() will return null because the Fragment is not attached yet to Activity. See the code below.

 fun Fragment.registerImagePicker(callback: ImagePickerResultListener): ImagePicker {
        return ImagePicker(callback, requireActivity())

To fix this you can move the initialization down in lifecycle Tree of Fragment after the fragment is attached for example inside onViewCreated() . Check fragment lifecycle.

class FragmentB : Fragment(), ImagePickerResultListener {

private lateinit var imagePicker: ImagePicker

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    imagePicker = registerImagePicker(this)

Leave a Reply