0

I've just started out with android and write a simple dialog app with some random strings presented to the user. I started to think about best way to do that?

if strings.xml consist of strings like:

<string name="quote1">blaha blaha</string>
<string name="quote2">chit chat</string>

I guess there's a better way then generating a random int and then do

case 1:
   R.id.quote1

I guess it will end up with at least 50 different quotes in that file, that's one ugly switch ..

Best regards

5 Answers 5

3

Try to get your quotes into a String array

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

2 Comments

You may want to explain a step further for explicitness: Then you can load the whole array into your activity with the getStringArray resources method (developer.android.com/reference/android/content/res/…) and randomly select from the array without the need for explicitly coding a switch for every resource ID. This is almost certainly the easiest way to go.
Sounds great, I'll try that out for sure!
1

If you cant use String Array then do this:

All .xml descriptor files in Android get compiled to your.package.R class.

You can use Java Reflection to inspect this class at runtime. In your case R.id is an inner static class.

Class clazz = R.id.class;
Field[] fields = clazz.getDeclaredFields();

// chose random field
int rnd = (int) (fields.length * Math.random());
String randomString = getString(fields[rnd].getInt(null));

Comments

0

Load your quotes into a list structure via xpath, select a random index from the list. Display that quote.

Alternately, get the count of quotes from the xml document, get a random index within that range, select the xml node at that index, and display it.

Comments

0

If you have only two strings its pretty simple, right. But if you have more, you might want to think about making a string array. You can make in XML easily.

Then just choose stringarray[random_number] as your string.

Comments

-1

There's a way to select a random item from a sequential list without knowing the length of the list.

The algorithm is:

numItems = 0;
selectedItem = null;
while not end of list
{
  item = read item from list
  numItems = numItems+1;
  if (numItems == 1)
    selectedItem = item;
  else  if (random(numItems) == 0)
    selectedItem = item
}

The idea is that there is always a 1/numItems probability that the new item will replace the currently selected item.

For more information, see my article Random Selection from Large Groups. Scroll down to "What if I don't know how many there are?" The code is in C#, but the discussion is language agnostic.

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.