Access application context in companion object in kotlin

Hafiz Hamza picture Hafiz Hamza · Jan 7, 2019 · Viewed 47.8k times · Source

How can we access application context inside companion object in Android kotlin? I have a companion object inside an abstract class and I want to access context to read Shared Preferences, but I'm not able to get the context.

UPDATE: I'm working with this stuff in an Android library and also the class that I'm working in is abstract

Answer

Raifur-rahim picture Raifur-rahim · Jan 7, 2019

please see this go to link

class MainApplication : Application() {

    init {
        instance = this
    }

    companion object {
        private var instance: MainApplication? = null

        fun applicationContext() : Context {
            return instance!!.applicationContext
        }
    }

    override fun onCreate() {
        super.onCreate()
        // initialize for any

        // Use ApplicationContext.
        // example: SharedPreferences etc...
        val context: Context = MainApplication.applicationContext()
    }
}