I edited the code the way @CommonsWare told me
i get force close when I try to click r1 and the problem is it seems button[i].isChecked() doesn;t work–> fixed
I have final RadioButton[] buttons = {r1,r3,r5,r7};
And I want to count them (basically yes answers)
public void onClick(View view){
checkStates(buttons);}
}
private void checkStates(RadioButton[] buttons) {
for (int i = 0; i < 4; i++) {
if (buttons[i].isChecked())
yes++;}
if (yes>=3){
Intent intent=new Intent(this,AnotherClass.class);
startActivity(intent);
}
}
Basically I have yes and no radio buttons. I want to count the yes answers and if the user changes their mind and checks no to decrement yes
r1 r3 r5 etc are “yes” answers
r2 r4 r6 are “no” answers
My approach might be wrong since I’m new to this but if someone helps me I’ll post the whole thing for people to see.
Please help!
Ok I checked the log cat and i receive the following error (it was obvious where but I don’t know why and how can I implement this to work)
Android Runtime: Uncaught handler :thread main exiting due to uncaught exception
java.lang.NullPointerException
RadioButtons.checkStates(RadioButtons.java:49) --> here : if (buttons[i].isChecked())
RadioButtons.onClick(RadioButtons.java:42)--> here: checkStates(buttons);
Edit:The problem – the way @CommonsWare pointed out-was that buttons wasn;t initialized and I got NullPointerException So I changed the code before with this one:RadioButton[]buttons =new RadioButton[3]; gave the size of the array
public void onClick(View view){
checkStates(buttons);
}
private void checkStates(RadioButton[] buttons) {
buttons[0]=rb1;
buttons[1]=rb3;
buttons[2]=rb5;
if (buttons[i].isChecked()){
yes++;}
tv.setText("Result:"+yes);
}
The problem this time is that It still counts the clicks and not the “yes” answers
I have the following problems to resolve
-
count the “yes” answers yes++
-
If the user clicks the second time don’t count
-
If the user changes their mind from “yes” to “no” decrement “yes”
-
If the user presses “no” Don’t count anything (the important part of my application is to count the yes answers )
Call
isChecked(). But you knew this already.There is no point in calling
setChecked(true)on aRadioButtonthat returns true fromisChecked(), since thatRadioButtonis already checked.Replace your
// if r1 or r3 are checked{withif buttons[i].isChecked() {