androidarrayskotlinlocalenumberpicker

How do I populate a number picker from a string-array (in the strings.xml)


I have a number picker and I can populate it with no problem from a regular array; however when I try to localize my app and place the array in the strings.xml file, that's when the frustration starts.

This is the strings.xml (partially)

<!--Set up arrays for the Number Pickers-->
    <string name="pieces">Pieces</string>
    <string name="kgs">Kgs</string>
    <string name="lbs">Lbs</string>
    <string name="oz">Oz</string>
    <string name="gal">Gal</string>
    <string name="liters">Liters</string>
    <string name="pints">Pints</string>
    <string name="quarts">Quarts</string>
    <string name="fl_oz">Fl Oz</string>

    <string-array name="all_units">
        <item>@string/pieces</item>
        <item>@string/kgs</item>
        <item>@string/lbs</item>
        <item>@string/oz</item>
        <item>@string/gal</item>
        <item>@string/liters</item>
        <item>@string/pints</item>
        <item>@string/quarts</item>
        <item>@string/fl_oz</item>
    </string-array>

Then in the MainActivity.kt, this is what I have:

val allUnits = arrayOf("Pieces","Kgs", "Lbs", "Oz", "Gal", "liters", "pints", "Quarts", "Fl oz")
npUnitsA.minValue = 0
npUnitsA.maxValue = allUnits.size -1

npUnitsA.displayedValues = allUnits

this works fine, but if I change that last line to:

npUnitsA.displayedValues = R.array.all_units

I get an error message: Type mismatch. Required:Array<(out) String!>! Found:Int

Needless to say I'm very green at Android. Any help will be greatly appreciated.


Solution

  • R.java contains identifiers in int so its expected to give this error. What you can do here is

     getResources().getStringArray(R.array.all_units)
    

    to get the resource array