DEV Community

Cover image for Resources(R.string) in viewModel in Android
Sandeep Satpute
Sandeep Satpute

Posted on

Resources(R.string) in viewModel in Android

I would like to share a technique to access the strings in view model that works well.
So there are multiple ways to access the string in view model but they have there own advantages and disadvantages.
We have options like

  1. Hardcode a string in code but this will not help in case of reusability and string localisation
  2. Use the context of an activity but in mvvm its bad practice to use context direct in view model
  3. Return the string resource id which is integer and in activity get the actual string but this will increase the efforts

Let's move toward the solution
In MVVM and hilt will have addition benefits to overcome above issue.

We will add the StringResourcesProvider.kt

@Singleton
class StringResourcesProvider @Inject constructor(
    @ApplicationContext private val context: Context
) {
    fun getString(@StringRes stringResId: Int): String {
        return context.getString(stringResId)
    }
}
Enter fullscreen mode Exit fullscreen mode

Define the view model to get the string

@HiltViewModel
class AuthViewModel @Inject constructor(
    private val stringResourcesProvider: StringResourcesProvider
) : ViewModel() {
    ...
    fun validate() {
        val username: String = stringResourcesProvider.getString(R.string.username)
    }
    ...
}
Enter fullscreen mode Exit fullscreen mode

In this way we can access the string in view model or any other places.

Thanks for reading my post.
Happy codding

Top comments (0)