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?

0

3 Answers 3

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

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

@Egor: Shouldn't String randomStr = array[new Random().nextInt(array.length)]; be String randomStr = array[new Random().nextInt(array.length - 1)]; to avoid ArrayIndexOutOfBoundsException?
@OsamaMohammedShaikh, Check the docs: docs.oracle.com/javase/7/docs/api/java/util/…
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.
I want random string but don't want to repeat...could you please help...? Thanks...!
@OsamaMohammedShaikh array.length - 1 is wrong. array.length is true
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.

1 Comment

This works too, accepted the other answer because it was first
-1
String[] myArrayOfStrings = {"one", "two", "three" } 
Random r = new Random();
String myRandString = r.nextInt(myArrayOfStrings.length );

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.