Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random value from a string array in android?

In my values.xml file, I have an array, like this;

<string-array name="animals-array">
    <item>Cow</item>
    <item>Pig</item>
    <item>Bird</item>
    <item>Sheep</item>
</string-array>

In my app, I want to get one of these values at random, but I am unsure how to do this. I have looked at

Help in getting String Array from arrays.xml file

and this

Retrieving a random item from ArrayList

But how do I retrieve a random item from my list that is defined in the values.xml file?

like image 848
jcw Avatar asked Jul 22 '12 11:07

jcw


People also ask

How to randomly Pick an Element from an array in Java?

Java has a Random class in the java. util package. Using it you can do the following: Random rnd = new Random(); int randomNumberFromArray = array[rnd.


1 Answers

String[] array = context.getResources().getStringArray(R.array.animals_array);
String randomStr = array[new Random().nextInt(array.length)];

Hope this helps.

like image 112
Egor Avatar answered Oct 05 '22 22:10

Egor