Reputation: 138824
I have created programmatically, 5 radio groups with 4 radio buttons each. Every radio button represents an answer to a question. So i want to do this. When someone checks the correct answers from the radio groups, i want to add all of them in an ArrayList
named correctAnswerRadios
. Same with the wrong answers. I set also a OnClickListener
on a button. I want also to make all the correct answers green and the wrong answers red, when someone presses the button. With this code, i get this error: 'java.lang.NullPointerException: Attempt to write to null array'.
Here is my code:
RadioGroup[] answerGroup;
RadioButton[] answer;
Button finishButton;
RadioButton[] checkedRadioButton;
ArrayList<RadioButton> correctAnswerRadios;
ArrayList<RadioButton> wrongAnswersRadios;
correctAnswerRadios = new ArrayList<>();
wrongAnswersRadios = new ArrayList<>();
answerGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
answerGroup[i] = new RadioGroup(this);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answer[j].setId(j + 100);
answer[j].setTag(String.valueOf(an.getCorrect_answer()));
answerGroup[i].addView(answer[j]);
answer[j].setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
@Override
public void onClick(View v) {
for (int j = 0; j < answer.length; j++) {
checkedRadioButton[j] = ((RadioButton) v);
int CorrectAnswer = Integer.parseInt(checkedRadioButton[j].getTag().toString());
if (checkedRadioButton[j].isChecked() & CorrectAnswer == 1) {
correctAnswerRadios.add(checkedRadioButton[j]);
} else {
wrongAnswersRadios.add(checkedRadioButton[j]);
}
}
}
});
j++;
}
}
linearLayout.addView(answerGroup[i]);
i++;
}
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < answerGroup.length; i++) {
for (int j = 0; j < answer.length; j++) {
RadioButton correctRadio = correctAnswerRadios.get(j);
correctRadio.setTextColor(Color.GREEN);
RadioButton wrongRadio = wrongAnswersRadios.get(j);
wrongRadio.setTextColor(Color.RED);
answerGroup[i].getChildAt(j).setEnabled(false);
}
}
}
});
Any help will be appreciated .Thanks!
Upvotes: 0
Views: 847
Reputation: 376
Init checkedRadioButton like
checkedRadioButton = new RadioButton[size];
and change your finishButton listener method to
public void onClick(View v) {
//Disable buttons
for (int i = 0; i < answerGroup.length; i++) {
for (int j = 0; j < answer.length; j++) {
answerGroup[i].getChildAt(j).setEnabled(false);
}
}
//put button colors
for(RadioButton correct: correctAnswerRadios){
correct.setTextColor(Color.GREEN);
}
for(RadioButton wrong: wrongAnswersRadios){
wrong.setTextColor(Color.RED);
}
}
Upvotes: 0
Reputation: 8520
You need to initialize your array. For instance:
checkedRadioButton = new RadioButton[size];
Upvotes: 1