Android. Get string resource for a non-activity class
You have to use reference to a Context to access resources. I'd recommend extending the Application class and creating an Application Singleton, then calling:
MyApplication.getInstance().getString(R.string.myString);
Or injecting it into your class of choice.
Problem with this approach is that it would make your class harder to test, since now it uses the Android context. I'd recommend passing a string as a dependency into the non-activity class of choice via the constructor or preferred method.
public MyClass(String string){
}
Related videos on Youtube
Santiago Gil
I am currently a fourth year undergraduate studying Computer Engineering at the University of Zaragoza. My score is 9.48, and I have been awarded with a total of 22 distinctions. My expectations are to get a Master's degree and then to doctorate.
Updated on June 04, 2022Comments
-
Santiago Gil almost 2 years
I have a String resource:
strings.xml <resources> <string name="myString">stringName</string> </resources>
How do I get the String from a non-activity-class?
I can't do
getResources().getString(R.string.myString)
-
Prerak Sola over 7 years
-
-
DJphy over 3 yearsthis doesnt work for locale change at runtime