I have followed Android Architecture Blueprints Dagger2 for dependency injection : https://github.com/googlesamples/android-architecture/tree/todo-mvp-dagger

Now I want to inject Adapter to my Fragment class :

@ActivityScoped
class MainFragment @Inject
constructor(): DaggerFragment() {

    @Inject lateinit var adapter : ArtistAdapter 
}

And I have following in the module class :

@Module
abstract class MainModule {
    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun mainFragment(): MainFragment

    @Module
    companion object {
        @Provides
        @ActivityScoped
        @JvmStatic internal fun provideArtistAdapter() = ArtistAdapter()
    }
}

But for some reason it fails to display data in RecyclerView. When I don't use injection and simply use val adapter = ArtistAdapter(), it works.

What am I missing in injection using Dagger2?

Addenda :

mainFragment is implementing a callback as a click listener:

interface ArtistClickCallback {
    fun onClick(artist: LastFmArtist, poster : ImageView)
}

And :

class MainFragment : DaggerFragment(), ArtistClickCallback

And here is fragment module :

@Module
class MainFragmentModule {

    @Provides
    fun provideArtistAdapter(mainFragment: MainFragment) = ArtistAdapter(mainFragment)

}

But I get following exception when I remove @Inject from Fragment constructor:

error: [Dagger/MissingBinding] com.sample.android.lastfm.ui.main.MainFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.sample.android.lastfm.LastFmApp> {
                ^
  A binding with matching key exists in component: com.sample.android.lastfm.ui.main.MainModule_MainFragment$app_debug.MainFragmentSubcomponent
      com.sample.android.lastfm.ui.main.MainFragment is injected at
          com.sample.android.lastfm.ui.main.MainActivity.mainFragment
      com.sample.android.lastfm.ui.main.MainActivity is injected at
          dagger.android.AndroidInjector.inject(T) [com.sample.android.lastfm.di.AppComponent ? com.sample.android.lastfm.di.ActivityBindingModule_MainActivity$app_debug.MainActivitySubcomponent]
Answer

Remove the @Inject from Fragment constructor and provide the adapter to the fragment or use an inject constructor in your adapter

@Module
abstract class MainModule {
    @FragmentScoped
    @ContributesAndroidInjector(modules = [MyAwesomeFragmentModule::class])
    internal abstract fun mainFragment(): MainFragment

} 

-

@Module
class MyAwesomeFragmentModule {

    @Provides
    fun provideArtistAdapter() = ArtistAdapter()

}
  • 1
Reply Report
    • Thank you @Ismael Di Vita. I am receiving an exception when I build. Please look at the addenda section in my question.

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions