Skip to content
Advertisement

Cannot be provided without an @Provides-annotated method (Dagger 2 in Android Kotlin)

searched on many sites and in various articles, but without effect, so I ask for your help with Dagger 2 (DI)

I can not understand what the problem is

I’m new to Dagger 2 (Di) and I’m just studying it, please help me understand

My code:

MainActivity.kt

class MainActivity : AppCompatActivity() {

    @Inject
    lateinit var networkService: NetworkService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        App().gerAppComponents().inject(mainActivity = this)

        setContentView(R.layout.activity_main)

        networkService.buildService(service = Movies::class.java).getPopularMovie(apiKey = "test", language = "en-US", page = 1)

    }

}

App.kt

class App : Application() {

    fun gerAppComponents(): AppComponent {
        return DaggerAppComponent.builder().appNetworkModule(AppNetworkModule())
            .build()
    }
}

ServiceBuild.kt

object ServiceBuild : NetworkService {
    private val client = OkHttpClient.Builder().build()

    private val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl("https://api.themoviedb.org/3")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    override fun <T> buildService(service: Class<T>): T = retrofit.create(service)
}

NetworkService.kt

interface NetworkService {
    fun <T> buildService(service: Class<T>): T
}

AppNetworkModule.kt

@Module
class AppNetworkModule {

    @Provides
    @Singleton
    fun getRetrofitService(): ServiceBuild {
        return ServiceBuild
    }
}

AppComponent.kt

@Singleton
@Component(modules = arrayOf(AppNetworkModule::class))
interface AppComponent {
    fun inject(mainActivity: MainActivity)
}

Build error

app/build/tmp/kapt3/stubs/debug/com/rebus/client/di/components/AppComponent.java:10: error: [Dagger/MissingBinding] com.rebus.client.services.impl.NetworkService cannot be provided without an @Provides-annotated method.
    public abstract void inject(@org.jetbrains.annotations.NotNull()
                         ^
      com.rebus.client.services.impl.NetworkService is injected at
          com.rebus.client.MainActivity.networkService
      com.rebus.client.MainActivity is injected at
          com.rebus.client.di.components.AppComponent.inject(com.rebus.client.MainActivity)

Advertisement

Answer

Change your code ServiceBuild to NetworkService like this:

@Module
class AppNetworkModule {

    @Provides
    @Singleton
    fun getRetrofitService(): NetworkService {
        return ServiceBuild
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement