Dagger hilt errror "lateinit property has not been initialized"

Viewed 1595

I am trying to inject a class in my fragment using field injection by it is giving me UninitializedPropertyAccessException when I try to access it in onViewCreated(). How can I fix this?

Class I am trying to inject:

@Singleton
class DialogHandler @Inject constructor() {

    private var currentDialogKey = "dialog_key"
    //....
    //....
}

My fragment:

@AndroidEntryPoint
class AccountFragment : Fragment(R.layout.fragment_account) {

    @Inject
    lateinit var dialogHandler: DialogHandler

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val currentDialogKey = dialogHandler.currentDialogKey // throws error saying dialogHandler is uninitialized
        //....
        //....
    }
}

Hilt has been setup correctly in the app and is working fine with constructor injection in other classes. But since constructor injection is not possible for fragments, I tried using field injection and got this error.
Please help.

Edit: This exception doesn't occur everytime. So it seems like this is a case of race condition where sometimes onViewCreated() is called before injection and sometimes after injection.

0 Answers
Related