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

In android development, you can store string values in the file app/res/values/strings.xml. Then refer to 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 the source file.
  2. Easy to maintain. If you want to change the 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 the string value of a meaningful name, then refer to the string value by the name in the 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 follow the below steps.

  1. Right-click app/res/values folder.
  2. Click New —> Values resource file menu in the popup menu list.
  3. Input strings in popup New Resource File dialog File name input text box, select main in the Source set drop-down list, and input values in the Directory name input text box.
  4. Click the OK button, then you can find the strings.xml file in the 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 to the string value in other XML files such as the 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 strings from strings.xml, you can follow the 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.