Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access getStringArray with a variable

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.

like image 368
Mairyu Avatar asked Apr 25 '26 07:04

Mairyu


1 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 :)

like image 104
Genesis Avatar answered Apr 27 '26 22:04

Genesis