Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String-array in Kotlin

Begin new project in Kotlin and missing those.

Try to get string-array recources but can't.

In strings.xml I palced next items.

<string-array name="themeList">
    <item>white</item>
    <item>sepia</item>
    <item>black</item>
    <item>pink</item>
</string-array>

In code I try next:

val res: Resources = resources
val appThemeList = arrayOf(res.getStringArray(R.array.themeList))

for (value in appThemeList) {
    Log.i ("value", value.toString())
}

But in logCat i see:

I/value: [Ljava.lang.String;@40145f2

And I don'r understand, what I do incorrectly.

like image 243
berliozz Avatar asked Feb 20 '18 09:02

berliozz


3 Answers

replace

val appThemeList = arrayOf(res.getStringArray(R.array.themeList))

to

val appThemeList = res.getStringArray(R.array.themeList)

In other case you got array

 val myArray = res.getStringArray(R.array.themeList) //already array

And added to another array

 arrayOf(myArray) // array of arrays
like image 83
Andrey Danilov Avatar answered Oct 06 '22 22:10

Andrey Danilov


In android is depend on context when outside Activity like this

val themes = context.resources.getStringArray(R.array.themeList)

or without context is direct to resource when inside Activity

val themes = resources.getStringArray(R.array.themeList)
like image 8
Subhanshuja Avatar answered Oct 06 '22 23:10

Subhanshuja


As we know res.getStringArray return arraylist so you do not need to write arrayOf on your code.

Simple way to achieve your goal is:-

val list = res.getStringArray(R.array.list);

We can use arrayOf when we have to define our array or we have already arraylist like below :-

val myArray = arrayOf(4, 5, 7, 3);
like image 3
duggu Avatar answered Oct 07 '22 00:10

duggu