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,

2 Answers 2

0

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

val rarity = resources.getStringArray(R.array.wp_rarity)
Sign up to request clarification or add additional context in comments.

3 Comments

I used getStringArray however it's highlighted in RED and doesn't seem to work.
Try to getResouce().getStringArray instead
Thanks, that was the answer ! To be more specific it was : resources.getStringArray(R.array.wp_rarity) Thank you very much !
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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.