NullPointerException
NullPointerException

Reputation: 37733

Which is the correct way to access Application class nowadays?

In the codelabs of modern android developers, they showed this way:

class CustomApplication: Application() {
    lateinit var container: AppContainer
    lateinit var context: Context

    override fun onCreate() {
        super.onCreate()
        container = AppContainer()
        context = applicationContext
    }
}

fun CreationExtras.CustomApplication(): CustomApplication=
    (this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as CustomApplication)

And access this way: CustomApplication().context

But it is giving me null in context, becuase onCreate is not being called for some reason. Another Android dev tell me that he things that code from the codelabs is wrong, and that it's creating new instances of application each time you are calling it. He told me to do it this way:

class CustomApplication: Application() {
    lateinit var container: AppContainer
    lateinit var context: Context

    override fun onCreate() {
        super.onCreate()
        instance = this
        container = AppContainer()
        context = applicationContext
    }

    companion object {
        lateinit var instance: CustomApplication
    }
}

And access this way: CustomApplication.instance.context

And it's working, but I'm not sure this is the correct way to use singleton pattern on Application class.. and also the IDE is giving me a warning on the instance variable:

Do not place Android context classes in static fields (static reference to CustomApplication which has field context pointing to Context); this is a memory leak

Which is the best way to access Application class nowadays?

Upvotes: 0

Views: 136

Answers (1)

Goni Schindler
Goni Schindler

Reputation: 35

This might be a matter of code taste but for me, the cleanest way is to inject the Application instance with Dagger Hilt when needed.

you can see a detailed example here: https://developer.android.com/training/dependency-injection/hilt-android

Upvotes: 0

Related Questions