So in android i want to make my application class a singleton.
Making it like this:
object MyApplication: Application(){}
won't work. Following erros is thrown at runtime:
java.lang.IllegalAccessException: private com....is not accessible from class android.app.Instrumentation.
Doing this is also not possible:
class MyApp: Application() { private val instance_: MyApp init{ instance_ = this } override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()); } } companion object{ fun getInstance() = instance_ } }
So how can i get an instance of my application class everywhere in my app, would like to use MyApp.instance()
instead of (applicationContext as MyApp)
.
Also an explanation why i want this: I have classes in my app, for example, a SharedPreference Singleton which is initialised with a context, and as its a singleton, can't have arguments.
If we especially conversation around Android, we know that in Android we by and large have to pass a context instance to init block of a singleton. We can do it by using Early initialization and Apathetic initialization. In early initialization, all the components are initialized within the Application.
The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
Using Singletons in Kotlin. By using the keyword object in your app, you're defining a singleton. A singleton is a design pattern in which a given class has only one single instance inside the entire app.
In Android App, for an object which is required to be created only once and use everywhere, we use the Singleton Pattern. Singleton Pattern is a software design pattern that restricts the instantiation of the class to only “one” instance.
You can do the same thing you would do in Java, i.e. put the Application
instance in a static field. Kotlin doesn't have static fields, but properties in objects are statically accessible.
class MyApp: Application() { override fun onCreate() { super.onCreate() instance = this } companion object { lateinit var instance: MyApp private set } }
You can then access the property via MyApp.instance
.
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