How To Read String Value Array From strings.xml In Android

In android development, you can store string values in app / res / values / strings.xml file. Then refer it in your java code. This can avoid hardcode string values in your xml or java source file.

1. Advantages Of Using strings.xml

  1. Avoid hardcode string value in source file.
  2. Easy to maintain. If you want to change string value, just need to change the value in strings.xml, do not need to change each source file.
  3. Easy to remember. You can give string value of meaningful name, then refer to the string value by the name in source file.

2. How To Create strings.xml.

Generally strings.xml is saved in app / res / values folder. If you can not find it there, you can create it by following steps.

  1. Right click app / res / values folder.
  2. Click New —> Values resource file menu in popup menu list.
  3. Input strings in popup New Resource File dialog as below.
    create strings.xml file in app res values folder
  4. Click OK button, then you can find strings.xml file in left panel tree.

3. Edit strings.xml File Content.

The content of strings.xml like below. The root xml element is resources. Each string xml element has a name attribute, this name is used in other xml or java source code files to get the string value.


    <string name="button_show_selection">Show Selection</string>

    <string name="auto_complete_text_view_car">Input Favorite Car Name</string>


4. Read String Value In Xml File.

Just use @string/string_value_name to refer it in other xml file such as layout xml file. Below is an example.

    android:text="@string/button_show_selection" />

5. Read String Value In Java Code.

String defaultInputText = getResources().getString(R.string.auto_complete_text_view_car);

6. Read String Array In Java Code.

If you want to read an array of string from strings.xml, you can follow below methods.

  1. Define a string array in strings.xml use string-array xml element.
        <string name="button_show_selection">Show Selection</string>
        <string name="auto_complete_text_view_car">Input Favorite Car Name</string>
        <string-array name="car_array">
  2. Read the string array in java source code. Please note car_array is just the string array name defined in strings.xml.
    String carArr[] = getResources().getStringArray(R.array.car_array);

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.