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?
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.
String[] array = context.getResources().getStringArray(R.array.animals_array);
String randomStr = array[new Random().nextInt(array.length)];
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With