How to randomly select from a string-array list
I have a list of string arrays:
<string-array name="chapter_1">
<item>......</item>
.
.
.
.
</string-array>
<string-array name="chapter_2">
<item>......</item>
.
.
.
.
</string-array>
etc. I have a random int chapter_no.
I have a line:
String chapter_name = "chapter_" + chapter_no;
Now I want to get an array of strings corresponding to chapter_no.
I know that I cannot do this:
String [] chapter =. GetResources () getStringArray (R.array.chapter_name);
How can I access string arrays randomly? Please help me.
Get a random line from chapter_array.
String[] chapter = getResources().getStringArray(R.array.chapter_name);
String randomString = chapter[new Random(chapter.length).nextInt()];
[Update]
String[] data;
//first of all give all resources to arrays
int[] arrays = {R.string.chapter_1, R.string.chapter_2};
//then we are fetching any one string array resources randomly
int chapter_no = arrays[new Random(arrays.length).nextInt()];
//From above we got any one random resource string..So we fetch all string items from that resource into data array
data = getResources().getStringArray(chapter_no);
//Now from that data array we fetch any one random string.
String randomString = data[new Random(data.length).nextInt()];
[updated]
String[] data;
int[] arrays = {R.array.chapter_1, R.array.chapter_2};
int chapter_no = arrays[new Random().nextInt(arrays.length-1)];
data = getResources().getStringArray(chapter_no);
String randomString = data[new Random().nextInt(data.length-1)];
Toast.makeText(this, randomString, Toast.LENGTH_SHORT).show();
You can do it:
String[] chapter = getResources().getStringArray(R.array.chapter_1);
String[] chapter2 = getResources().getStringArray(R.array.chapter_2);
Random rand=new Random();
int randomNo=rand.nextInt();
ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(chapter));
temp.addAll(Arrays.asList(chapter2));
String [] concatedArgs = temp.toArray(new String[chapter.length+chapter2.length]);
String item=concatedArgs[randomNo];