0

How can I get a random question in java from the resource file using following xml:

<array name="question1">
    <item name="id">1</item>
    <item name="question">Question 1?</item>
    <item>@array/possible_answers1</item>
    <item name="correct_answer">1</item>
</array>
    <string-array name="possible_answers1">
        <item>Answer1</item>
        <item>Answer2</item>
        <item>Answer3</item>
        <item>Answer4</item>
    </string-array>

<array name="question2">
    <item name="id">2</item>
    <item name="question">Question 2?</item>
    <item>@array/possible_answers2</item>
    <item name="correct_answer">3</item>
</array>
    <string-array name="possible_answers2">
        <item>Answer1</item>
        <item>Answer2</item>
        <item>Answer3</item>
        <item>Answer4</item>
    </string-array>

To get the first question in java I use:

String[] str_quest = res.getStringArray(R.array.question1);
str_question = str_quest[1];

but how can I get random question? Thanks for reading!

2 Answers2

0

This will work:

Random rand = new Random();
int numberOfQuestion = 3;//For example
int randomQuestionID = this.getResources().getIdentifier("question"+rand.nextInt(numberOfQuestion), "array", this.getPackageName());
str_question = res.getStringArray(randomQuestionID)[1];
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
0

Create an Integer Array of all id's of question array:

int[] question_arr=new {R.array.question1,R.array.question2,...};
Random randnum = new Random();

Get random array id from question_arr:

int question_index=question_arr[randnum.nextInt(question_arr.length)];
String[] str_quest = res.getStringArray(question_index);
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213