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.
- Creat a
lateinit
Context field inside companion object.
abstract class MyClass { companion object { private lateinit var context: Context fun setContext(con: Context) { context=con } } }
- 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
Post a Comment