1

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,

Daniel Morena
  • 101
  • 1
  • 2
  • 5

2 Answers2

0

You should use getStringArray instead of arrayOf. It is method of collections. Try this

val rarity = resources.getStringArray(R.array.wp_rarity)
Công Hải
  • 4,961
  • 3
  • 14
  • 20
0

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 !

Daniel Morena
  • 101
  • 1
  • 2
  • 5