How to create a static array of strings in Android (example)

Android FAQ: How can I create a static array of strings in Android?

It turns out that it’s easy to create and use a static array of strings in Android. Of course you can do this in Java code, as I describe in my Java string array tutorial, but for Android I’m talking about doing this in XML.

In short, this is how you define a static string array in an Android XML file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="my_books">
        <item>Scala Cookbook</item>
        <item>Play Framework Recipes</item>
        <item>How I Sold My Business: A Personal Diary</item>
        <item>A Survival Guide for New Consultants</item>
    </string-array>
</resources>

Then inside an Activity, Fragment, or other Java class, you can create a string array in Java from that XML like this:

Resources res = getResources();
String[] myBooks = res.getStringArray(R.array.my_books);

Where to put the static String array

For small apps you can put your string array in the usual res/values/strings.xml file, but in larger apps your static string array doesn’t have to be declared in the strings.xml file; you can put your array in any XML file in the res/values directory, as long as it has the format shown.

Another example: Using a static string array in a ListPreference

I was just working through an Android “Preferences” example, and saw where the author defined two static string arrays in a file named res/values/array.xml, like this:

<resources>
    <string-array name="listArray">
        <item>Headings</item>
        <item>Headings and Details</item>
        <item>All Data</item>
    </string-array>
    <string-array name="listValues">
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>
</resources>

Instead of accessing his string arrays in Java code, he access them in XML in a ListPreference, like this:

<ListPreference android:title="Download Details"
                android:summary="Select the kind of data that you would like to download"
                android:key="downloadType"
                android:defaultValue="1"
                android:entries="@array/listArray"
                android:entryValues="@array/listValues" />

That’s another cool use of a static string array in Android, and it comes from this Android preferences tutorial.

Summary

In summary, if you needed to see how to define a static string array in XML in an Android app, I hope this example is helpful.