Solution 1 :
You should use getStringArray
instead of arrayOf
. It is method of collections. Try this
val rarity = resources.getStringArray(R.array.wp_rarity)
Solution 2 :
The answer was given by Cong Hai in the comments of his post.
It was :
val rarity = resources.getStringArray(R.array.wp_rarity)
Many thanks to him !
Problem :
I searched for a way to display in my TextView a random string from my array list stored in Values/Rarity.xml.
There are many examples here all in Java, but none are working.
I tried:
kotlin Get random string from array (can’t make it work with an array from my values/rarity.xml)
Getting random values from an ArrayList
I am new to Android studio and would like to know how to make it work, has I’ve been trying for the past few hours without success.
This is what I would like to achieve, but the app crash when I click on the button :
package com.example.myapplication
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rarity = arrayOf(R.array.wp_rarity)
val randomRarity = rarity.random()
btn_generate.setOnClickListener {
item_type.setText(randomRarity)
}
}
}
If I replace the val rarity = arrayOf(R.array.wp_rarity)
by val rarity = arrayOf("test", "test2")
it does work but I would like to use my arrays in values/*.xml in order to optimize it. Or is there another way ?
Regards,
Comments
Comment posted by Daniel Morena
I used getStringArray however it’s highlighted in RED and doesn’t seem to work.
Comment posted by Công Hải
Try to getResouce().getStringArray instead
Comment posted by Daniel Morena
Thanks, that was the answer ! To be more specific it was :