Home > Software engineering >  Dagger 2 Unable to provide and inject Interface and its implementation in android
Dagger 2 Unable to provide and inject Interface and its implementation in android

Time:10-24

@Module
abstract class  PersonUsecaseModule{
    @Provides
    internal fun provideUseCase(useCase: GetPersonUseCaseImpl): PersonUseCase = useCase

    @Provides
    internal fun provideMutableLiveData() = MutableLiveData<PersonUseCase.Result>()

    @Provides
    internal fun providePersonWidgetImplScreen(widget: PersonWidgetImpl): PersonWidget = widget

}

this is my module class and i am injecting it in MainActivity i am getting error

error: com.anil.gorestapp.person.injection.PersonUsecaseModule is abstract and has instance @Provides methods. Consider making the methods static or including a non-abstract subclass of the module instead. public abstract interface ApplicationComponent {

I don't know why i am getting this Error Please help me what i am doing mistake

lateinit var personWidget: PersonWidget

AppLication component :

@Singleton
@Component(
        modules = [

            ApplicationModule::class,
            ActivityModule::class,
            NetworkModule::class
        ]
)
interface ApplicationComponent {
    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun build(): ApplicationComponent
    }

    fun inject(application: MainApplication)
}
     

ActivityModule

abstract class ActivityModule {

    @ContributesAndroidInjector
    abstract fun contributeMainActivity(): MainActivity

    @Binds
    abstract fun bindSharedPreferences(appPreferenceImpl: AppPreferenceImpl): AppPreference

}

person module

abstract class ActivityModule {

    @ContributesAndroidInjector
    abstract fun contributeMainActivity(): MainActivity

    @Binds
    abstract fun bindSharedPreferences(appPreferenceImpl: AppPreferenceImpl): AppPreference

}

CodePudding user response:

So the issue is, You have declared your module as "abstract" and along with this, you are also using @Provides annotation on methods which are returning implementation of interface.

Dagger doesn't allow that. You can fix this issue in two way:

First Way: Remove abstract from your module like this:

@Module
class ActivityModule {
@Provides
fun providePersonWidget(personWidget: PersonWidgetImpl) : PersonWidget = personWidget
}

Second way: Use @Bind annotation on method instead of provide like this

@Module
abstract class ActivityModule {
@Binds
abstract fun providePersonWidget(personWidget: PersonWidgetImpl) : PersonWidget
}

Note: In second way you can declare your method and class as abstract but cannot return anything.

If you are still not very clear with my answer, you can refer this branch which I have created for you.

https://github.com/parmeshtoyou/StackOverflow/compare/sof_23_oct_21_dagger_issue?expand=1

Happy coding!

  • Related