10

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?

Naresh NK
  • 1,036
  • 1
  • 9
  • 16

1 Answers1

19
@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.

Naresh NK
  • 1,036
  • 1
  • 9
  • 16
Saeid Lotfi
  • 2,043
  • 1
  • 11
  • 23
  • A related subject @SaeedLotfi... you have enough reputation in `dagger-hilt` tag to upvote synonyms. Could you do that here: https://stackoverflow.com/tags/dagger-hilt/synonyms ? No moderator seem to care about bringing order to `hilt` related tags, so I'm trying to coordinate that myself. – Bartek Lipinski Aug 15 '20 at 08:14