Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly select a string from strings.xml in Android

Tags:

android

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?

like image 407
user1537814 Avatar asked Aug 27 '12 09:08

user1537814


Video Answer


2 Answers

  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);

like image 156
Wayne Avatar answered Oct 24 '22 20:10

Wayne


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.

like image 21
Zak Chapman Avatar answered Oct 24 '22 19:10

Zak Chapman