Search code examples
kotlinandroid-viewbindingkotlin-lateinit

Lateinit property viewBinding has not been initialized


I'm using viewBinding successfully and never encountered this problem before. The property is initialized in onViewCreated like so:

private lateinit var viewBinding: FragmentMainBinding

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // Create a binding object to the layout
    viewBinding = FragmentMainBinding.bind(view)
}

I then have a button which opens the camera, like so (also in onViewCreated):

// Button to open camera
viewBinding.takePictureButton.setOnClickListener {
    findNavController().navigate(R.id.action_main_fragment_to_camera)
}

My main fragment implements an interface function declared in the camera fragment. This is to know whether the user picked an image or dismissed the camera without picking an image. Like so:

// Interface declared in CameraFragment
interface ImageCaptureListener {
    fun onUserDismissedCamera(userPickedImage: Boolean)
}

// Implementation of interface function in main fragment
override fun onUserDismissedCamera(userPickedImage: Boolean) {
    if(userPickedImage) {
        println("User picked image")
        
        //** The app crashes when trying to set image in viewBinding.mainFragmentImageView

    } else {
        println("User did NOT picked image")
    }
}

How can my viewBinding property not be initialized here? It obviously is when navigating to camera fragment. Is this a lifecycle issue of some sort? Is it deinitialized when navigating to camera?

Thankful for any pointers.


Solution

  • View is destroyed when you are navigating to another Fragment, so binding is not valid anymore. Normally this would be solved by setting retainInstance to true in the Fragment onViewCreated, but it is deprecated now (although I disagree with deprecation, but Google noobs only think that apps can be simple only so reloading complex layouts now will be an expensive thing). You can use retainInstance, or set the returned photo object from the callback to some variable and set it when onCreateView is called.