John Kaita
John Kaita

Reputation: 5

How to define context in a kotlin object

How can I define a context for the progressdialog within such an object

import dmax.dialog.SpotsDialog

object Constants {
    //These are all the constants within our application
    const val permission_request = 100
    val firebaseAuth = FirebaseAuth.getInstance()
    val progressDialog = SpotsDialog.Builder().setContext(thecontext).build()
}

Upvotes: 0

Views: 1275

Answers (1)

Tenfour04
Tenfour04

Reputation: 93571

You can give it a lateinit context property that you set in your Application class. Then make the property that's dependent on it Lazy. But in this case, it doesn't make sense, because a Dialog is transient. It wouldn't be a constant. You can't reuse dialogs, because Android destroys and recreates the Activities/Fragments that host them according to various lifecycle processes.

But if you do have something like a constant that needs a Context, this is how you could do it:

object Constants {
    lateinit var context: Context
    val foo by lazy { Foo(context) }
}

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        Constants.context = this
    }
}

And make sure you set .MyApplication as the Application name in the manifest.

Upvotes: 1

Related Questions