Search code examples
androidkotlindagger-2picasso

Why not show data when use Dagger2 on Android


In my application i want use Dagger2 and i want show just one image from server and for show image i used Picasso.
I write below codes, but after run application not show me any image into imageview!
For android i use Kotlin language.

Application class :

class App : Application() {

    var component: AppComponent? = null

    override fun onCreate() {
        super.onCreate()
        //Init dagger component
        component = DaggerAppComponent.builder().modulePicasso(ModulePicasso(this)).build()
    }

    fun getAppComponent(): AppComponent? {
        return component
    }
}

Activity class :

class MainActivity : AppCompatActivity() {

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

        App().getAppComponent()?.getPicasso()?.load("https://cdn01.zoomit.ir/2017/6/5f0e97c1-9eb7-4176-aa02-35252489ede8.jpg")
            ?.into(imageView)
    }
}

How can i fix it?


Solution

  • I think it's because you are creating a new instance of you application class, eg. App() and then calling getAppComponent() which for sure returns null, as you should not construct the application instance yourself, but instead access a static property referencing it.

    To fix it, you need to add a static property (instance) to the App class and get the AppComponent using that property.