Leandro Borges Ferreira
Leandro Borges Ferreira

Reputation: 12782

Dagger + Kotlin not injecting

I studying Dagger 2 for DI and I just did this code to inject the Retrofit:

NetModule.kt

@Module
class NetModule(val baseUrl: String) {

    @Provides
    @Singleton
    fun provideRetrofit() : Retrofit{
        [some logic here]
    }
}

AppModule.kt

@Module
class AppModule(val mApplication: Application) {

    @Provides
    @Singleton
    fun provideApplication() : Application{
        return mApplication
    }
}

NetComponent.kt:

@Singleton
@Component(modules = arrayOf(AppModule::class, NetModule::class))
interface NetComponent {
    fun inject(activity: Activity)
}

CustomApplication.kt

class CustomApplication : Application() {

    companion object {
        lateinit var mNetComponent: NetComponent
    }

    override fun onCreate() {
        super.onCreate()

        AndroidThreeTen.init(this)

        mNetComponent = DaggerNetComponent.builder()
                            .appModule(AppModule(this))
                            .netModule(NetModule(getString(R.string.api_base_url)))
                            .build()

    }
}

Then in my activity:

class TrashCansInfoActivity : AppCompatActivity(){

@Inject
    lateinit var mRetrofit: Retrofit

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

        CustomApplication.mNetComponent.inject(this)

        setSupportActionBar(toolbar)

        populateTrashCanList()

    }

    private fun populateTrashCanList(){
        showProgress(true)
        mRetrofit.create(ApiClient::class.java)
                .getTrashCans()
                .map { it.map { it.toTrashCan() } }
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError {
                    showProgress(false)
                    Toast.makeText(this, "Erro ao carregar lista de lixeiras", Toast.LENGTH_SHORT).show()
                }.doOnCompleted { showProgress(false) }
                .subscribe(behaviorSubject)
    }

}

So, this code should work, right? The dependency should be added... But when I run my app... I get this:

kotlin.UninitializedPropertyAccessException: lateinit property mRetrofit has not been initialized

So the Retrofit is not being injected. What am I missing?

Any help is welcome!

Upvotes: 13

Views: 7717

Answers (2)

anoo_radha
anoo_radha

Reputation: 822

I got the same error. The mistake was - not injecting the component. Also i had to inject the component in a fragment. (in kotlin)

val component = (activity?.application as MyApplication).appComponent component.plus(FakeModule(this)).inject(this)

This solved the error.

Upvotes: 3

EpicPandaForce
EpicPandaForce

Reputation: 81539

fun inject(activity: Activity)

should be

fun inject(activity: TrashCansInfoActivity)

Upvotes: 20

Related Questions