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

Please say "thank you" by commenting on this post!

Everyone is welcome

Top comments (0)

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 →

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay