Android. Get string resource for a non-activity class

11,789

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){
}
Share:
11,789

Related videos on Youtube

Santiago Gil
Author by

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, 2022

Comments

  • Santiago Gil
    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)

  • DJphy
    DJphy over 3 years
    this doesnt work for locale change at runtime