How do you access the values in the res/values/string.xml resource file from the Android Activity class?
5 Answers
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();
}
10 Comments
Ravikiran
<string-array name="planet"><item>Mercury</item><item>Venus</item> <item>Earth</item></string-array> for this code while i use getString(R.string.planets);
Ravikiran
I checked your answer but I got ForceClose error. Thanks for helping
Ravikiran
THIS IS LOGCAT 08-27 20:16:04.844: ERROR/AndroidRuntime(339): FATAL EXCEPTION: main 08-27 20:16:04.844: ERROR/AndroidRuntime(339): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.string/com.string.string}: android.content.res.Resources$NotFoundException: String resource ID #0x7f050000
Ravikiran
THIS IS LOGCAT 08-27 20:16:04.844: ERROR/AndroidRuntime(339): FATAL EXCEPTION: main 08-27 20:16:04.844: ERROR/AndroidRuntime(339): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.string/com.string.string}: android.content.res.Resources$NotFoundException: String resource ID #0x7f050000 08-27 20:16:04.844: ERROR/AndroidRuntime(339): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
KrisWebDev
Note that getString() is not static. If you want to assign a string.xml value to a static property of your app class, do it in you class onCreate().
|
strings.xml:
<string name="some_text">Some Text</string>
Activity:
getString(R.string.some_text);
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>