How should I get Resources(R.string) in viewModel in Android (MVVM and databinding)

Shubham picture Shubham · Dec 4, 2017 · Viewed 25.7k times · Source

I am currently using databinding and MVVM architecture for android. What would be the best way to get string resources in ViewModel.

I am not using the new AndroidViewModel component, eventbus or RxJava

I was going through the aproach of interfaces where Activity will be responsible for providing resources. But recently I found a similar question with this answer where a single class using application context is providing all resources.

Which would be the better approach? or is there something else that I can try?

Answer

Expert wanna be picture Expert wanna be · Dec 6, 2017

You can access the context by implementing AndroidViewModel instead of ViewModel.

class MainViewModel(application: Application) : AndroidViewModel(application) {
    fun getSomeString(): String? {
        return getApplication<Application>().resources.getString(R.string.some_string)
    }
}