I am having trouble fixing the following issue:
I am making a small quiz android app. I have a QuizActivity and a QuizFragment, I build a list of QuizFragments in the activity:
questionFragments = new ArrayList<>();
questionFragments.add(QuestionFragment.newInstance(new Question("Amai menne ...",
new ArrayList<Answer>() {{
add(new Answer("Frak", false));
add(new Answer("Jas", true));
add(new Answer("Bernadette", false));
}})));
questionFragments.add(QuestionFragment.newInstance(new Question("Question 2",
new ArrayList<Answer>() {{
add(new Answer("Answer 1", false));
add(new Answer("Answer 2", true));
}})));
I have a method in the activity that replaces the current QuestionFragment:
private void showQuestion(int question) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content_quiz_fl_question, questionFragments.get(question));
transaction.commit();
}
Callback in the QuestionActivity:
@Override
public void onCorrectAnswerSelected() {
showQuestion(currentQuestion + 1);
}
In my QuestionFragment I build the RadioGroup programmatically (OnCreateView):
radioGroup = new RadioGroup(getContext());
radioGroup.setOrientation(RadioGroup.VERTICAL);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, R.id.fragment_question_tv_title);
radioGroup.setLayoutParams(lp);
for (Answer answer : question.getAnswers()) {
RadioButton radioButton = new RadioButton(getContext());
radioButton.setText(answer.getAnswer());
radioButton.setPadding(0, 30, 0, 30);
radioGroup.addView(radioButton);
}
I have a listener on the button of the fragment:
verifyAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (question.getAnswers().get(checkedRadioButtonId - 1).isCorrect()) {
//Correct
handleSuccess();
} else {
//Incorrect
handleFailure();
}
}
});
Now this is where I am having an issue, when I answer the first question everything works as planned but when I answer my second question the app crashes. I was able to pinpoint the problem with the help of debugging. I seems that the RadioGroup "remembers" the possible answers from the previous questions (in this case I selected the second option from the second question). You can see below that the selected radioButtonId is 5 but I only have 2 radio buttons:
I would appreciate any help! Source code: https://github.com/Jdruwe/ElineBirthday