1

I need to access a random string array. The problem is that this gives me an exception. "Invalid int."

    wordArray = getResources().getStringArray(Integer.valueOf("R.array" + array[new Random().nextInt(array.length)]));

Any other way to do this? I can't seem to find one. Please help me. Thanks in advance.

8
  • 4
    You are trying to call Integer.valueOf() on a string thats not an integer... Commented Jul 30, 2014 at 2:45
  • Integer.valueOf() does not make sense. That's sure. Maybe wordArray = getResources().getStringArray("R.array." + array[new Random().nextInt(array.length)]); could do it, but I won't put my money on it Commented Jul 30, 2014 at 2:47
  • 1
    Why don't you store the resource ids in array instead of ... whatever you store in there right now. Commented Jul 30, 2014 at 2:48
  • 3
    possible duplicate of Randomly select a string from strings.xml in Android Commented Jul 30, 2014 at 2:50
  • 2
    As stated from timrau's link, use getResources().getIdentifier() to get the resource ID from a given name. You should probably be able to continue from there. Or just declare an array for resource ID as suggested by fabian. Commented Jul 30, 2014 at 2:54

1 Answer 1

0

Put your arrays into an ArrayList, then use Random to select one of the values within the array. Selecting a random value with the "R" file is not a good idea - your arrays may not be in numeric order. The Resource file is not generated always in an order that is intuitive or reliable for the code you have written.

Pseudo code to initialize the array:

ArrayList<String[]> randomArray = new ArrayList<String[]>();
int arrayCount = 0;
randomArray.add(getResources().getStringArray(R.array.Array1));
// continue adding arrays

Then use a random integer to select an array from randomArray based on its length. Since you are using "res" StringArrays, you can't have an indefinite number of arrays, otherwise your problem would be more complex.

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

1 Comment

I've already solved the problem with the getIdentifier() function. :) Your method wouldn't work for me very well. My arrays are indeed not in numeric order but that doesn't matter because I created an extra array which contains the name of all the arrays I need. That's the array I'm taking a random string from.

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.