Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access application context in companion object in kotlin

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

like image 769
Hafiz Hamza Avatar asked Jan 07 '19 13:01

Hafiz Hamza


People also ask

How do you get the context inside the companion object?

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.

What is Applicationcontext in Kotlin?

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.

How do you use the companion object in Kotlin?

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.

What is difference between object and companion object in Kotlin?

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.


1 Answers

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()     } } 
like image 85
Raifur-rahim Avatar answered Sep 21 '22 06:09

Raifur-rahim