Damien Cooke
Damien Cooke

Reputation: 713

Static like methods in Android application with kotlin

I am trying to add a "static" method to my MyApplication class in kotlin I have added (as a property) the variable :

private var context: Context? = null

in method:

override fun onCreate()

I added:

context = applicationContext

then I add a companion object like this

companion object {
    @JvmStatic fun getMyApplicationContext(): Context?
    {
        return MyApplication().context
    }
}

when I call this method from other parts of the application like MyApplication.getMyApplicationContext() it always returns null. I have gleaned all this from several sources but I am not sure if it is anywhere near correct or not.

Upvotes: 1

Views: 3201

Answers (1)

Michael Anderson
Michael Anderson

Reputation: 73480

It sounds like you want a global application context object. Now casting aside my dislike for global variables, I think you are pretty close.

I think you just need to add the variable into the MyApplication classes companion object and use that directly. You only need the @JvmField annotation if you're going to access the field from Java.

class MyApplication {
   companion object {
      @JvmField
      var context: Context? = null

      // Not really needed since we can access the variable directly.
      @JvmStatic fun getMyApplicationContext(): Context? {
        return context
      }
   }

   override fun onCreate() {
     ...
     MyApplication.context = appContext
   }
}

Upvotes: 4

Related Questions