Search code examples
androidkotlindagger-2dagger

lateinit property androidInjector has not been initialized Dagger 2


I have the application like this

class App : Application() , HasAndroidInjector {

    lateinit var application: Application

    @Inject
    lateinit var androidInjector : DispatchingAndroidInjector<Any>

    override fun androidInjector(): AndroidInjector<Any> = androidInjector

    override fun onCreate() {
        super.onCreate()
        this.application = this
    }
}

Then I have the AppComponent

@Singleton
@Component(
    modules = [
        AndroidSupportInjectionModule::class,
        LoginModule::class
    ]
)
interface AppComponent : AndroidInjector<App> {

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance application: App): AppComponent
    }
}

LoginModule is this

@Module
abstract class LoginModule {

    @ContributesAndroidInjector(modules = [LoginDependencies::class])
    abstract fun bindLoginFragment(): LoginFragment
}

And in the onViewCreated of the Fragment I'm using

AndroidSupportInjection.inject(this)

I also have tried to add it on the onAttach() but it does not work. It started to crash once I added the

@Inject
lateinit var loginPresenter: LoginContract.Presenter

If I remove it, it says the same as the question, if I leave the presenter it says that preseter is not being initialized.

Is something I'm missing?

Edit

Where I'm getting this error

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property androidInjector has not been initialized

override fun androidInjector(): AndroidInjector<Any> = androidInjector

Then I'm getting this also

at com.testing.login.login.presentation.LoginFragment.onRequestInjection(LoginFragment.kt:31)

AndroidSupportInjection.inject(this)

This onRequestInjection is in a AbstractFragment in the onViewCreated also I've tried to put it on onAttach() but nothing changed.

And my build.gradle contains :

this in the :app

    api(LibrariesDependencies.DAGGER)
    api(LibrariesDependencies.DAGGER_ANDROID)
    api(LibrariesDependencies.DAGGER_ANDROID_SUPPORT)
    kapt LibrariesDependencies.DAGGER_ANDROID_KAPT
    kapt LibrariesDependencies.DAGGER_KAPT
    kapt LibrariesDependencies.DAGGER_ANNOTATION_PROCESSOR

and on :login

api(LibrariesDependencies.DAGGER)
    api(LibrariesDependencies.DAGGER_ANDROID)
    api(LibrariesDependencies.DAGGER_ANDROID_SUPPORT)
    kapt LibrariesDependencies.DAGGER_ANDROID_KAPT
    kapt LibrariesDependencies.DAGGER_KAPT
    kapt LibrariesDependencies.DAGGER_ANNOTATION_PROCESSOR


Solution

  • Is the property that hasn't been initialized happening in the App class? If so, this likely means that you're missing the following in the onCreate method of the App class.

    DaggerAppComponent
                .factory()
                .create(this)
                .inject(this)