Access string.xml Resource File from Java Android Code

JavaAndroidString

Java Problem Overview


How do you access the values in the res/values/string.xml resource file from the Android Activity class?

Java Solutions


Solution 1 - Java

Well you can get String using,

getString(R.string.app_name);

And, you can get string-array using

String arr[] = getResources().getStringArray(R.array.planet);
for (int i = 0; i < arr.length; i++) {
      	Toast.makeText(getBaseContext(),arr[i], Toast.LENGTH_LONG).show();	
}

Solution 2 - Java

strings.xml:

<string name="some_text">Some Text</string>

Activity:

getString(R.string.some_text);

Solution 3 - Java

Put this code in res/values/string.xml

<string-array name="planet"> 
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
</string-array>

This code to be placed in res/layout/main.xml and remove default widgets present in main.xml.

<ListView android:id="@+id/planet"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:entries="@array/planet"/>
</LinearLayout>

Solution 4 - Java

If getString(R.string.app_name); isn't working for you, you can pass context like this:

context.getString(R.string.app_name);

Solution 5 - Java

If you have the context of Activity, go with:

getString(R.string.app_name);

If you don't have the context, try below, you can get the context from activity using Constructor.

mContext.getString(R.string.app_name);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavikiranView Question on Stackoverflow
Solution 1 - JavaLalit PoptaniView Answer on Stackoverflow
Solution 2 - JavaOllie CView Answer on Stackoverflow
Solution 3 - JavaRavikiranView Answer on Stackoverflow
Solution 4 - JavaBilbo BagginsView Answer on Stackoverflow
Solution 5 - JavagauravsngargView Answer on Stackoverflow