Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger with Hilt inject ActivityContext in adapter from module

I'm using dagger and hilt and i want to inject @ActivityContext from a module to an Adapter but i'm getting this error -

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1/mnt/My Projects/app/build/generated/source/kapt/debug/app/myapp/MyApp_HiltComponents.java:156: error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ActivityContext android.content.Context cannot be provided without an @Provides-annotated method.
  public abstract static class ApplicationC implements MyApp_GeneratedInjector,
                         ^
      @dagger.hilt.android.qualifiers.ActivityContext android.content.Context is injected at
          app.myapp.di.modules.activitiesModules.HomeActivityModule.provideAdapterFragmentState(context)
      app.myapp.ui.base.AdapterFragmentState is injected at
          app.myapp.ui.home.HomeActivity.adapterFragmentState
      app.myapp.ui.home.HomeActivity is injected at

This is my HomeActivityModule -

@Module
@InstallIn(ActivityRetainedComponent::class)
object HomeActivityModule {

    @Provides
    @ActivityRetainedScoped
    fun provideAdapterFragmentState(@ActivityContext context: Context): AdapterFragmentState {
        return AdapterFragmentState(context)
    }

}

And this is my Adapter -

@ActivityRetainedScoped
class AdapterFragmentState @Inject constructor(@ActivityContext context: Context)
    : FragmentStateAdapter(context as AppCompatActivity){

Which part is wrong?

like image 749
Naresh NK Avatar asked Jul 11 '20 15:07

Naresh NK


1 Answers

@Module
@InstallIn(ActivityComponent::class)
object HomeActivityModule {

    @Provides
    @ActivityScoped
    fun provideAdapterFragmentState(@ActivityContext context: Context): AdapterFragmentState {
        return AdapterFragmentState(context)
    }

}

Edited :

Because ActivityRetainedComponent lives across configuration changes and ActivityComponent doesn't.

If you want to inject @ActivityContext, your module should be installed in ActivityComponent and the injected objects must be @ActivityScoped.

like image 193
Saeed Lotfi Avatar answered Sep 27 '22 17:09

Saeed Lotfi