0

I am trying to access a string indicating an API key from Resources through my viewModel class mapViewModel by having an application class named AppUtils with the method getKey() which returns the string resource.

*I do not want to pass any context/activity to the viewModel in order to keep the code around the MVVM architecture :

class AppUtils : Application() {

    fun getKey() = resources.getString(R.string.google_maps_key)
 }

viewModel:

class MapViewModel : ViewModel() {
    private val appKey = AppUtils().getKey()

when running the project i get an error saying that the resources object i am referring to is null

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

any suggestions? Thanks !

Yarin Shitrit
  • 297
  • 4
  • 16
  • 2
    Just use AndroidViewModel: https://stackoverflow.com/questions/44148966/androidviewmodel-vs-viewmodel – Pawel Sep 02 '20 at 19:59
  • lol its a little funny because AndroidViewModel requires an application in its constructor so.. of course i will have access to the application xD but how do i initialize in activity an AndroidViewModel and pass an application to its constructor? – Yarin Shitrit Sep 02 '20 at 20:05
  • same way you obtain a normal viewmodel, default factory recognizes AVM and fills in the application argument for you – Pawel Sep 02 '20 at 20:12

0 Answers0