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
A) Provide the context as an argument to all functions that need it. B) Instead of a Singleton companion object, create an instance of the class and provide the context as a constructor argument. Consider closing / cleaning up the instance, when not used anymore.
Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only. Activity Context: It is the activity and we are present in Activity. For example - MainActivity.
To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.
Object expressions are executed (and initialized) immediately, where they are used. Object declarations are initialized lazily, when accessed for the first time. A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a Java static initializer.
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() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With