Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Singleton Application Class

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.

like image 243
johnny_crq Avatar asked May 23 '16 12:05

johnny_crq


People also ask

How do you make a singleton class in Kotlin?

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.

What is Kotlin application class?

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.

What is singleton in Android Kotlin?

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.

What is the use of singleton class in Kotlin?

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.


1 Answers

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.

like image 80
Kirill Rakhman Avatar answered Sep 25 '22 06:09

Kirill Rakhman