Access Application Context In Companion Object In Kotlin


Answer :

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()     } } 

Actually I'm working inside an Android library and the class is abstract, so can't go with the already suggested solutions. However, I found way to do that.

  1. Creat a lateinit Context field inside companion object.
abstract class MyClass {      companion object {          private lateinit var context: Context          fun setContext(con: Context) {             context=con         }     } } 
  1. And then set it after the app has started
public class WelcomeActivity extends AppCompatActivity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_welcome);          MyClass.Companion.setContext(this);     } } 

Extends Application class like this

import android.app.Application import android.content.Context  class MyApplication : Application() {  override fun onCreate() { super.onCreate() MyApplication.appContext = applicationContext  }  companion object {  lateinit  var appContext: Context  } } 

then get context like this

     val context = MyApplication.appContext 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?