In AndroidViewModel, how to use the received application property?

0

Issue

A simple AndroidViewModel looks like

class AppViewModel(application: Application) : AndroidViewModel(application) {...}

Now, to access the application property all over the model, we need to add a val/var to it (per my knowledge).

class AppViewModel(val application: Application) : AndroidViewModel(application) {...}

This however gives error, saying

Accidental Override: The following declarations have the same JVM signature: getApplication()

How do I get around this?

Solution

You already have access, you can use this property inside your class:

private val db = SomeDB.getInstance(application)

but not inside class methods, you must pass it manually:

fun myViewModelMethod(application: Application = application, ...) {}

However, you can declare new property inside your viewmodel:

class AppViewModel(application: Application) : AndroidViewModel(application) {
    val app = application
...
}

and use it anywhere inside.

Answered By – bylazy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More