0

i developing a quiz wherein i have 50 questions stored and i want it to display random in the quiz everytime the user will play..how can i do that? is it possible to randomize question using json?please help me.. i really appreciate ur help..thanks.

public class Question1 extends Activity {

Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.question10);

    Thread thread = new Thread() {
        public void run() {
            try {
                Thread.sleep(1 * 1000);
                finish();
                loadQuestions();
                Intent intent = new Intent(Question1.this,
                        Question2.class);
                Question1.this.startActivity(intent);
            } catch (Exception e) {
            }
        }
    };
    thread.start();

}

private void loadQuestions() throws Exception {
    try {
        InputStream questions = this.getBaseContext().getResources()
                .openRawResource(R.raw.questions);
        bReader = new BufferedReader(new InputStreamReader(questions));
        StringBuilder quesString = new StringBuilder();
        String aJsonLine = null;
        while ((aJsonLine = bReader.readLine()) != null) {
            quesString.append(aJsonLine);
        }
        Log.d(this.getClass().toString(), quesString.toString());
        JSONObject quesObj = new JSONObject(quesString.toString());
        quesList = quesObj.getJSONArray("Questions");
        Log.d(this.getClass().getName(),
                "Num Questions " + quesList.length());
    } catch (Exception e) {

    } finally {
        try {
            bReader.close();
        } catch (Exception e) {
            Log.e("", e.getMessage().toString(), e.getCause());
        }

    }

}

public static JSONArray getQuesList(){

    return quesList;



}

}

public class Question2 extends Activity {
/** Called when the activity is first created. */


TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.startquiz);


    try {

        items = (TextView)findViewById(R.id.displayitems);
        question = (TextView) findViewById(R.id.displayquestion);
        answer1 = (RadioButton) findViewById(R.id.option1);
        answer2 = (RadioButton) findViewById(R.id.option2);
        answer3 = (RadioButton) findViewById(R.id.option3);
        answers = (RadioGroup) findViewById(R.id.QueGroup1);


        next = (Button) findViewById(R.id.selected);
        next.setOnClickListener(nextListener);

        selected = new int[Question1.getQuesList().length()];
        java.util.Arrays.fill(selected, -1);
        correctAns = new int[Question1.getQuesList().length()];
        java.util.Arrays.fill(correctAns, -1);

        this.showQuestion(0, review);



    } catch (Exception e) {
        Log.e("", e.getMessage().toString(), e.getCause());
    }

}

private void showQuestion(int qIndex, boolean review) {
    try {
        JSONObject aQues = Question1.getQuesList().getJSONObject(
                qIndex);
        String quesValue = aQues.getString("Question");
        if (correctAns[qIndex] == -1) {
            String correctAnsStr = aQues.getString("CorrectAnswer");
            correctAns[qIndex] = Integer.parseInt(correctAnsStr);
        }

        question.setText(quesValue.toCharArray(), 0, quesValue.length());
        answers.check(-1);
        answer1.setTextColor(Color.BLACK);
        answer2.setTextColor(Color.BLACK);
        answer3.setTextColor(Color.BLACK);
        JSONArray ansList = aQues.getJSONArray("Answers");
        String aAns = ansList.getJSONObject(0).getString("Answer");
        answer1.setText(aAns.toCharArray(), 0, aAns.length());
        aAns = ansList.getJSONObject(1).getString("Answer");
        answer2.setText(aAns.toCharArray(), 0, aAns.length());
        aAns = ansList.getJSONObject(2).getString("Answer");
        answer3.setText(aAns.toCharArray(), 0, aAns.length());
        Log.d("", selected[qIndex] + "");
        if (selected[qIndex] == 0)
            answers.check(R.id.option1);
        if (selected[qIndex] == 1)
            answers.check(R.id.option2);
        if (selected[qIndex] == 2)
            answers.check(R.id.option3);

        setText();
        if (quesIndex == (Question1.getQuesList().length() - 1))
            next.setEnabled(false);

        if (quesIndex < (Question1.getQuesList().length() - 1))
            next.setEnabled(true);

        if (review) {
            Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
            ;
            if (selected[qIndex] != correctAns[qIndex]) {
                if (selected[qIndex] == 0)
                    answer1.setTextColor(Color.RED);
                if (selected[qIndex] == 1)
                    answer2.setTextColor(Color.RED);
                if (selected[qIndex] == 2)
                    answer3.setTextColor(Color.RED);
            }
            if (correctAns[qIndex] == 0)
                answer1.setTextColor(Color.GREEN);
            if (correctAns[qIndex] == 1)
                answer2.setTextColor(Color.GREEN);
            if (correctAns[qIndex] == 2)
                answer3.setTextColor(Color.GREEN);
        }
    } catch (Exception e) {
        Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
    }
}


private void setAnswer() {
    if (answer1.isChecked())
        selected[quesIndex] = 0;
    if (answer2.isChecked())
        selected[quesIndex] = 1;
    if (answer3.isChecked())
        selected[quesIndex] = 2;



    Log.d("", Arrays.toString(selected));
    Log.d("", Arrays.toString(correctAns));

}

private OnClickListener nextListener = new OnClickListener() {
    public void onClick(View v) {
        setAnswer();

        for(int i=0; i<correctAns.length; i++){

            if ((correctAns[i] != -1) || (correctAns[i] == selected[i]))
            {
                if (correctAns[i] == selected[i])
                score++;
                Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
            }else
        {
            Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
        }

        quesIndex++;
        if (quesIndex >= Question1.getQuesList().length())
            //quesIndex = Question1.getQuesList().length() - 1;

        showQuestion(quesIndex, review);
        }

    }
};
private void setText() {
    this.setTitle("Question     " + (quesIndex + 1) + "out of     "
            + Question1.getQuesList().length());
    items.setGravity(250);
}

public void reload() {

Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();

overridePendingTransition(0, 0);
startActivity(intent);
}

}

4
  • but literally i suggest you that you should be use Colection.shuffle() function rather then Math.random() bcz some time question is repeated. Its my personal opinion.... Commented Feb 19, 2013 at 12:46
  • Random has its own limitation it will repeat after 2^48 calls. (it uses a 48-bit seed). But it doesn't mean its not random enough. Commented Feb 19, 2013 at 12:54
  • @rajesh.adhi,is it possible to limit the display of the question? wherein i have 50 question stored and then i want only 10 question to display Commented Feb 20, 2013 at 9:46
  • int index = (int)(Math.random() * 10); and when one question is loaded you have to reduce the count by 1 means after loading of one question it should be int index = (int)(Math.random() * 9);. Also if you want to start the question from 20th index you can give like 20 + (int)(Math.random() * 10); Commented Feb 20, 2013 at 10:56

1 Answer 1

0

Use ((int) Math.random() * <size of your array>) to generate a random index for your array of questions

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

2 Comments

thanks so much....it such a great help!but where can i put that ((int) Math.random() * <size of your array>) @pandre
I guess if you don't know that probably the code you pasted is not yours and you just want us to code it for you

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.