8

I need to randomly select a string defined within strings.xml file in android.

For example my strings.xml is :

<resources>
    <string name="str1">Content comes here1</string>
    <string name="str2">Content comes here2</string>
    <string name="str3">Content comes here3</string>
</resources>

Can I randomly select one of these strings in my Activity?

3 Answers 3

8
  1. Create an array contains all of your resource names you want to select:

    String[] strs = new String[] {"str1", "str2", "str3"};

  2. Get a random index:

    int randomIndex = new Random().nextInt(3);

  3. Get your random string from resource:

    int resId = getResources().getIdentifier(strs[randomIndex ], "string", your_package_name);

    String randomString = getString(resId);

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

1 Comment

Since the strings are resources, you could do int[] strs = {R.string.str1, R.string.str2, R.string.str3}; and then in step 3 do int resId = strs[randomIndex];
7

The best way is you declare you Strings as an Array, then get it like this:

String[] arrayOfStrings = context.getResources().getStringArray(R.array.your_string_array);
String randomString = arrayOfStrings[new Random().nextInt(arrayOfStrings.length)];

Then you can use it as you like.

Comments

0

You would probable rather make it an array of strings (and then that is easier to select at random one of the array). Else, you can put the ids of your strings in an array and randomly select one of the items in the array.

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.