Reputation: 10523
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.
Upvotes: 5
Views: 3514
Reputation: 1
Make sure to first call super.onViewCreated(view, savedInstanceState)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val currentDialogKey = dialogHandler.currentDialogKey
//....
}
I had a similar problem in an activity. In my case, I was accessing a field, which should have been injected by Hilt using field injection in the onCreate
method, before calling super.onCreate(savedInstanceState)
.
In my case, calling super.onCreate(savedInstanceState)
first and then accessing the injected field solved the problem.
This is probably because the base class should be firstly initialized and only after that Hilt performs the injection of dependencies.
Upvotes: 0