DEV Community

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

Posted on

5 1 1 1

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

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay