yong8521
yong8521

Reputation: 21

Dagger2 not working in android

I have problem using dagger2

I create Component, Module, Provide

class testModule {
    @Provides @Singleton
    fun provideTestServer(): TestService {
    }
}

and i called onCreate() in MainActivity

DaggerImageComponent.builder().build().inject(this)

here's my problem DI works fine in MainActivity

class MainActivity: AppCompatActivity {
    @Inject
    lateinit var testService: TestService
}

but other file is not working.

object TestObject {
    @Inject
    @JvmSynthetic // error: static field cannot inject
    lateinit var testService: TestService
    fun test() = testService.testfun()
}

or

@Singleton
class TestClass {
    @Inject
    lateinit var testService: TestService
    fun test() = testService.testfun()
}

TestClass and TestObject get error - lateinit property testInterface has not been initialized

i don't understand why error occured in TestClass, TestObject.

Upvotes: 1

Views: 347

Answers (1)

A. Shevchuk
A. Shevchuk

Reputation: 2169

You should call "inject" inside of class where you want to get injected variable. You did it for MainActivity, but also you should inject your component inside other classes. By the way, you have TestClass, it seems like you use it in client code also from injection, because it has "Singleton" annotation. If it's true - you can simply add provider for it in your module and pass service as a contructor parameter:

class testModule {
    @Provides @Singleton
    fun provideTestServer(): TestService {
    }

 @Provides @Singleton
    fun provideTestServer(testService: TestService): TestClass {
    }
}

then, your TestClass should have constructor:

class TestClass(var testService: TestService) {
    fun test() = testService.testfun()
}

I suggest you to read once again about dagger, check this tutorial: http://www.vogella.com/tutorials/Dagger/article.html

Upvotes: 1

Related Questions