0

I would like to know how to obtain the value from a string getString(R.string) in an external class.

Matthew
  • 1,905
  • 3
  • 19
  • 26
  • This site accepts questions in English only. – elixenide Aug 17 '15 at 23:58
  • 1
    These sites are places where you can ask or answer Android application development questions in Spanish: http://www.andglobe.com/#es. (Google Translate: Estos sitios son lugares donde se puede hacer o contestar preguntas de desarrollo de aplicaciones para Android en español: http://www.andglobe.com/#es) – CommonsWare Aug 17 '15 at 23:58
  • 1
    The most obvious way is to pass context to this class constructor initializer. You can declare global context in application extending class and make it static but it's not the most elegant way – Sebastian Pakieła Aug 18 '15 at 00:23
  • See this answer: https://stackoverflow.com/questions/4391720/how-can-i-get-a-resource-content-from-a-static-context/4391811#4391811 This is the best solution, in my opinion. --- But you can also do this: https://stackoverflow.com/a/8765789/8312196 – River Jun 24 '19 at 11:30

3 Answers3

0

Do something like this:

Java Code:

String string = getString(R.string.hello);

strings.xml:

<resources>
    <string name="hello">Hello!</string>
</resources>
Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
0

You can do it this way:

public static class OtherClass{

    public static void getString(Context mContext){
        String str = mContext.getString(R.string.app_name);
        Log.i("String value", str);
    }

}

How to call from Activity:

OtherClass.getString(this);
Matthew
  • 1,905
  • 3
  • 19
  • 26
Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
0

You need context to use getString(..) method in any class.

Make one MyApplication.java class file.

public class MyApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

Add name argument in Application tag in manifest file like,

<application
   android:name=".MyApplication"
   android:icon="@mipmap/ic_launcher"
   ....

And then in you any class you can use below line to use getString(..) method.

String string = MyApplication.getContext().getString(...);
DHAVAL A.
  • 2,251
  • 2
  • 12
  • 27