Search code examples
androidkotlincompanion-object

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


Solution

  • 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);
        }
    }