I have created programmatically, 5 radio groups with 4 radio buttons each. I set OnClickListener
on the reset button that i have created too. I want when someone clicks the button, to restart my activity. How is it even possible? When the app first time starts, it works fine but when i press the button to reload the activity, the emulator crashes. If i comment the lines where i create the radio groups and the radio buttons and i press the button, the activity is reloading fine otherwise i have this error: Unable to start activity ComponentInfo{...}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
. How can reload the activity without issues? Here is my code:
answerGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
answerGroup[i] = new RadioGroup(this);
answerGroup[i].setOrientation(RadioGroup.VERTICAL);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answerGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(answerGroup[i]);
i++;
}
restartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
Thanks!
The activity is probably trying to reference to old view elements (from before the Activity restart). Try to add your view components:
As class variables. Can you try that and tell me what it is doing? I will update this answer according to the input you give me.
EDIT:
I assume that you are using a ArrayList<Question>
and ArrayList<Answer>
as the questions
and answers
variable.
for (Question qn : questions) {
RadioGroup answerGroup = new RadioGroup(this);
answerGroup.setOrientation(RadioGroup.VERTICAL);
for (Answer an : qn.getAnswers()) {
if (qn.getID() == an.getQuestion_id_answer()) {
RadioButton answer = new RadioButton(this);
answer.setText(an.getAnswer());
answerGroup.addView(answer);
}
}
linearLayout.addView(answerGroup);
}
Maybe you should add a getter method to your question called: getAnswers();
and a variable to your Question
model called List<Answer> answers
. Ofcourse, these answers need to be set before you try to do anything with them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments