I have a fragment class as follows:
class MainFragment : Fragment(R.layout.main_fragment) {
@Inject lateinit var runner: Runner
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
runner.runProcess()
}
}
Here is my Runner.java file:
public class Runner {
@Inject
public Runner(@ApplicationContext Context applicationContext) {
// some setup code
}
public runProcess() {...}
}
I am getting an error at the runner.runProcess() line saying that lateinit property runner is not initialized . I am using Hilt in my Android app. How can I go about fixing this?
MainActivity.kt:
@AndroidEntryPoint
class MainActivity @Inject constructor() : AppCompatActivity(R.layout.activity_main) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
supportFragmentManager.commit {
setReorderingAllowed(true)
add<MainFragment>(R.id.fragment_container_view);
}
}
}
}
Found the issue. I have to add the @AndroidEntryPoint
annotation to my fragment as well, despite the fragment being added to the main activity which has this annotation.
For future reference, the @AndroidEntryPoint
annotation should be provided for every android class which requires dependency injection. It marks the entry points for hilt to inject modules. It is not to be confused with the entry point of the app ie, the launch activity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.