Home > database >  Kotlin error: Dagger does not support injection into static fields
Kotlin error: Dagger does not support injection into static fields

Time:04-13

i tried to use Dagger for dependency injection in my Retrofit project, but when I build the code it throws this error : Dagger does not support injection into static fields. Does anyone have any idea why I get this error? i cant figure out what I did wrong.

MianActivity.kt:

@Inject
lateinit var  mApiService : ApiService

class MainActivity : AppCompatActivity() {



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var retroComponent = DaggerRetroComponent.create()
        retroComponent.inject(this)
}

RetroComponet.kt

@Singleton
@Component(modules = [ServiceBuilderModule::class])
interface RetroComponent {
    //Field Injection
    fun inject(mainActivity: MainActivity)
}

ServiceBuilder.kt

@Module
object ServiceBuilderModule {
    val baseUrl = "https://dog-facts-api.herokuapp.com"


    @Singleton
    @Provides
    fun retrofitInstance(): Retrofit {
        return Retrofit.Builder().baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Singleton
    @Provides
    fun getRetroServiceInterface(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }

ApiService.kt

interface ApiService {
    @GET("/api/v1/resources/dogs")
    suspend fun getDogFact(@Query("index") index: String): Response<List<DogFactModel>>

}

CodePudding user response:

Replace:

@Inject
lateinit var  mApiService : ApiService

class MainActivity : AppCompatActivity() {

with:

class MainActivity : AppCompatActivity() {

@Inject
lateinit var  mApiService : ApiService

mApiService needs to a property within MainActivity, not a top-level property.

  • Related