Reputation: 3349
I have an activity layout with multiple choice questions. My goal is to only have to use one activity, and for the layout to refresh with new choices after every question is answered. However, I lay it out in a while loop
like below, and my hope was that the onClickListener
for the radio buttons would stall the while loop and wait for a user to pick an option and then update the UI accordingly, but instead the screen just goes black.
I've tried using the debugger and it stops as soon as it gets to the while loop, but I have no idea why.
private void play(){
int questionCount = 1;
while(questionCount < 20) {
Question question = new Question();
final Game game = new Game();
String[] questions = new String[5];
final int temp = questionCount;
questions = game.getQuestions(questionCount);
A.setText(questions[0]);
B.setText(questions[1]);
C.setText(questions[2]);
D.setText(questions[3]);
E.setText(questions[4]);
group.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int answer = group.getCheckedRadioButtonId();
boolean correct = game.checkAnswer(answer, temp);
}
});
questionCount++;
}
}
Upvotes: 0
Views: 146
Reputation: 11
Android has it's own event loop so you don't need to create your own.
A better implementation would be to set up your view in your Activity's onCreate method to display the initial question and set up the OnClickListener for your answer button. That click listener could then call a class that handles answer checking and getting the next question.
Example:
class QuizManager {
private int mCurrentQuestion;
String[] mQuestions;
//TODO: create constructor to initialize variables
public bool checkAnswer(int answer){
//TODO: check answer logic
return isAnswerCorrect;
}
public String getNextQuestion(){
mCurrentQuestion++;
//TODO: handle the case for the last question
return mQuestions[mCurrentQuestion];
}
}
Now your method could look something like this:
private void play(){
//This should probably be a member variable in your Activity
QuizManager manager = new QuizManager();
mQuestionTextView.setText(getNextQuestion();
group.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int answer = group.getCheckedRadioButtonId();
if (manager.checkAnswer(answer)){
mQuestionTextView.setText(getNextQuestion());
}
}
});
}
Upvotes: 1
Reputation: 1982
Instead of using a loop, use a logic that would update the screen with the new question on clicking one of the radio buttons, i.e, the screen should update with the new question through a call from the onClickListener
instead of the while
loop.
Upvotes: 2