Home > Mobile >  How to Pair Item in String Array?
How to Pair Item in String Array?

Time:10-23

I have a long string array list of "Animals" that I need to associate a code number with. Once the "Animal" is selected via my spinner the value is stored in a variable. I also want to have the associated code number stored in its own variable. How do I go about creating this "pairing" without writting a ton of if/then code. Can I do anything within my strings.xml file that contains my string-array?

        <string-array name="Animals">
          <item>Dog</item>
          <item>Cat</item>
          <item>Mouse</item>
          ...

"Dog" paired with code: "111" "Cat" paired with code: '222" "Mouse" paired with code:"333"

CodePudding user response:

You can create the corresponding integer-array and zip them together. There is one BIG WARNING with this though, you have to make sure that if you change one of the arrays, you must update the other too!

Kotlin playground example:

fun main() {
    val stringArray: Array<String> = arrayOf("Dog", "Cat")
    val intArray: Array<String> = arrayOf("1", "0")
    print(sArray.zip(iArray))
}

If the corresponding code is going to be only their index in the array it's simple as:

arrayOf("Dog", "Cat").mapIndexed { index, animal -> index to animal }

So with your example it would be something like this:

<string-array name="Animals">
      <item>Dog</item>
      <item>Cat</item>
      <item>Mouse</item>
      ...
</string-array>

<integer-array name="AnimalsNumberCodes">
      <item>111</item>
      <item>222</item>
      <item>333</item>
      ...
</integer-array>

val listOfPairs = resources.getStringArray(R.array.Animals)
    .zip(
        resources.getIntArray(R.array.AnimalsNumberCodes).toTypedArray()
     )
  • Related