Home > Back-end >  Get the index number of ArrayList Kotlin
Get the index number of ArrayList Kotlin

Time:09-23

I wanted to know the index number of an array so tried as shown below.

val countryCodeList = arrayListOf(*resources.getStringArray(R.array.countryCodes))
val countryIndex = countryCodeList.indexOf(" 1")

And it only returns true(0) & false(-1). If string " 1" locates on the 4th row of the list, I want it to return 3 for the result.

How can I receive the index number of an arrayList?

Log

array : [ 82, Korea]
result: -1
==================================================
array : [ 60, Malaysia]
result: -1
==================================================
array : [ 1, USA]
result: 0

CodePudding user response:

Issue might be, you are not assigning string items to array properly.

Try below code, it should work

Your resource file should like

`<resources>
<string name="app_name">Sample</string>
    <string-array name="countryCodes">
        <item name="KR">@string/korea_number</item>
        <item name="MY">@string/malaysia_number</item>
        <item name="AU">@string/indonesia_number</item>
        <item name="SG">@string/singapore_number</item>
        <item name="CA">@string/us_number</item>
        <item name="NZ">@string/new_zealand_number</item>
    </string-array>

<string name="korea_number"> 92</string>
<string name="malaysia_number"> 91</string>
<string name="indonesia_number"> 99</string>
<string name="singapore_number"> 93</string>
<string name="us_number"> 94</string>
<string name="new_zealand_number"> 98</string> </resources>`

On your activity file or fragment file you can access like this

val countryCodeList = arrayListOf(*resources.getStringArray(R.array.countryCodes)) val countryIndex = countryCodeList.indexOf(" 99")

`println("countryIndex $countryIndex")`

if you want, you can replace appropirate country codes.

CodePudding user response:

Simply use:

val countries = resources.getStringArray(R.array.countryCodes)
val index = countries.indexOf(" 1")

CodePudding user response:

Here I share my final solution for anyone in need. It only returned 0 or -1 because my string was not exactly same as the value on the array list.

Solution

I used filter function and called the value which contains my string. Then, I used replace and deleted "[" and "]". Finally, I could have the exactly same string as the value on array list and now it gives me the index number of the string that I am looking for.

  • Related