Home > Blockchain >  In AndroidViewModel, how to use the received application property?
In AndroidViewModel, how to use the received application property?

Time:01-06

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?

CodePudding user response:

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.

  •  Tags:  
  • Related