Reputation: 422
I am new to Hilt and have never use dagger properly. I get the following error.
[Dagger/MissingBinding] retrofit2.Retrofit cannot be provided without an @Inject constructor or an
@Provides-annotated method.
I have annotated my provideRetrofit Method with @provides and have installed it in Application Component. I want to inject it in my main activity and have used the inject annotation there. I tried installing it in activity component but still same result.
Here is my Retrofit Module.
@Module
@InstallIn(ApplicationComponent::class)
class RetrofitModule {
@Singleton
@Provides
fun provideGson(): Gson {
return GsonBuilder().create()
}
@Singleton
@Provides
fun provideRetrofit (gson: Gson): Retrofit{
return Retrofit.Builder().baseUrl("Base Url")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build()
}
}
In my Main Activity I have written this to inject it.
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var retrofit: Retrofit
Upvotes: 5
Views: 3767
Reputation: 111
Try to change your code like this:
@Module
@InstallIn(ApplicationComponent::class)
Object RetrofitModule {
@Singleton
@Provides
fun provideRetrofit (gson: Gson): Retrofit{
return Retrofit.Builder().baseUrl("Base Url")
.addConverterFactory(
GsonConverterFactory.create(GsonBuilder().create())
)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build()
}
}
Instead of creating class try to create object. Don't create Gson in seperate function. i have got this error too when i am using moshi converter.
Upvotes: 2
Reputation: 4712
I think your Retrofit return Type is wrong. Try this (it worked for me):
@Singleton
@Provides
fun provideRetrofit (gson: Gson): Retrofit.Builder() {
return Retrofit.Builder()
.baseUrl("Base Url")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
}
EDIT: Oh and change class RetrofitModule
to object RetrofitModule
! Otherwise, the @Provides
is never executed. And please bear in mind that you can use your retrofit only after onCreate()
Upvotes: 0