How do we access strings resources outside the fra...
# android
a
How do we access strings resources outside the fragment or activity. I am doing the following:
Copy code
App.context.getString(R.string.rupees, min.toString())
But with application context static reference like that I am not able to change the strings based upon locale. How should update the app context or restart the whole app? Can anyone help?
d
where do you need string resources?
a
In a model class.
d
You should pass a string to the model class when creating an instance of the model class instead of using resources directly in the model class
a
I am doing it like
Copy code
fun priceRange(): String {

// Return 1 price if min & max is same
        if (min == max) {
            return "${App.context.getString(R.string.rupees, min.toString())}"
        }
}
One option is to pass the context as param of function from the calling activity or fragment. But I will then have to add it all over the places in code. Can I updated or reset app context to get latest resources when Locale is changed?
a
No, you cannot. You must use the more local context for this. In upcoming Android versions more things will continue to require more local contexts to function, such as an activity or service context.
👍 2
d
@Aness Iqbal To avoid passing the context around, can you have
min
and
max
data in the model class and then create that string in the
Activity/Fragment
or in the
Presenter/ViewModel
if you’re using any architectural pattern?
👍 2
1
a
Thanks @Dean Djermanović and @Adam Powell. And yes I am following MVVM.
j
I would rather use the resource as an Int in my model, and then access it on the view by using binding, I don't know if I get what you are doing, but I guess you just want to have the reference of your resource, use a when to decide what resource you need and return the resource itself, then show up in your UI. Also remember that you can do this sort of logic (concatenation) at your view level (xml).
👍 1
437 Views