16

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?

Community
  • 1
  • 1
jcw
  • 5,132
  • 7
  • 45
  • 54

3 Answers3

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

Hope this helps.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • @Egor: Shouldn't `String randomStr = array[new Random().nextInt(array.length)];` be `String randomStr = array[new Random().nextInt(array.length - 1)];` to avoid `ArrayIndexOutOfBoundsException`? – Osama Mohammed Shaikh Jun 14 '16 at 11:36
  • 1
    @OsamaMohammedShaikh, Check the docs: https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int) – Egor Jun 14 '16 at 11:44
  • 1
    Ok it excludes specified value, i.e. n value. I checked Android docs but that was not so clear, so had a doubt. Well thanks for clearing the doubt. – Osama Mohammed Shaikh Jun 14 '16 at 11:48
  • I want random string but don't want to `repeat`...could you please help...? Thanks...! – VikaS GuttE Feb 22 '19 at 09:12
1

1. Retrive the Complete String Array from the xml and put it inside an ArrayList using Arrays.asList() method.

2. Use Math.random()*mArr.size() function to get a random number. (mArr is the ArrayList)

3. Then use this random number to get an animal from the ArrayList like

   `myArr.get(myrand);`

4. The reason i suggested the use of ArrayList (ie Collection framework) cause that will give you more flexibility.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
-1
String[] myArrayOfStrings = {"one", "two", "three" } 
Random r = new Random();
String myRandString = r.nextInt(myArrayOfStrings.length );
Frank Eno
  • 2,581
  • 2
  • 31
  • 54