Skip to content Skip to sidebar Skip to footer

Randomly Select A String From Strings.xml In Android

I need to randomly select a string defined within strings.xml file in android. For example my strings.xml is : Content comes here1&l

Solution 1:

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

Solution 2:

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.

Solution 3:

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.

Post a Comment for "Randomly Select A String From Strings.xml In Android"