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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more