How do I access getStringArray with a variable

Viewed 159

I'm sure there's a perfect fine way to do this much better, but basically what I want is to create 2-dim array via strings.xml.

ie. I have a main category:

<string-array name="main_categories">
    <item>index_etf</item>
    <item>region_etf</item>
    <item>commodity_etf</item>
</string-array>

and a bunch of subcategories:

<string-array name="index_etf">
    <item>DOW</item>
    <item>NASDAQ</item>
</string-array>

instead of doing it hardcoded like:

    MainCategoryArray = getResources().getStringArray(R.array.main_categories);
    IndexETFArray = getResources().getStringArray(R.array.index_etf);
    ...

I'd like to do something like:

    MainCategoryArray = getResources().getStringArray(R.array.main_categories);

    loop through the main array and populate the sub categories

Not sure if I can access the getStringArray with an int variable based on the content of the MainCategoryArray, is there?

Any better approach to build a multi-dimensional based on strings.xml? Sorry, new to this.

2 Answers

Try this,

Variable declaration

private final static String TAG = MainActivity.class.getSimpleName();
private ArrayList<String> mainCategoryArray;
private ArrayList<ArrayList<String>> categoryArrays  = new ArrayList<>();

Usage

 mainCategoryArray = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.main_categories)));
    for(String mainCategory : mainCategoryArray){
        try {
            categoryArrays.add(new ArrayList<>(Arrays.asList(getResources().getStringArray(getResources().getIdentifier(mainCategory, "array", getPackageName())))));
        } catch (Resources.NotFoundException e){
            Log.e(TAG, e.toString());
        }
    }

Sample strings.xml array

<string-array name="main_categories">
    <item>index_etf</item>
    <item>region_etf</item>
    <item>commodity_etf</item>
</string-array>

<string-array name="index_etf">
    <item>DOW</item>
    <item>NASDAQ</item>
</string-array>

<string-array name="region_etf">
    <item>DOW</item>
    <item>NASDAQ</item>
</string-array>

<string-array name="commodity_etf">
    <item>DOW</item>
    <item>NASDAQ</item>
</string-array>

Hope this helps :)

You can use qualifiers on resources so android itself choose appropriate resources based on the qualifiers. For example you can have values-small for small screens and values-large for large screen and values for other screen sizes. You can see all available qualifiers here.

Related