Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Retrofit using Hilt

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
like image 610
Aditya Kurkure Avatar asked Nov 16 '22 05:11

Aditya Kurkure


1 Answers

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.

like image 140
Rachman Abda'u Avatar answered Dec 15 '22 05:12

Rachman Abda'u