Guy
Guy

Reputation: 6522

Uncheck all checkboxes with button click

I'm currently making an app with a lot of checkboxes (39 to be spcific) and I want to implement a button that will uncheck them when it's clicked. I haven't done much with buttons (I only used them to start a new activity so far) so I'm still not completely sure how they work. After doing some research this is what I came up with. Even though I have 39 checkboxes I will only paste a few in this code to keep it short.

CheckBox cb1 = (CheckBox) findViewById(R.id.checkBox2);
CheckBox cb2 = (CheckBox) findViewById(R.id.checkBox3);
CheckBox cb3 = (CheckBox) findViewById(R.id.checkBox4);
public void onClick (View v){
    switch (v.getId()) {
        case R.id.button1:
            cb1.setChecked(false);
            cb2.setChecked(false);
            cb3.setChecked(false);
    }
}

LogCat:

06-12 06:45:09.922: E/AndroidRuntime(6623): FATAL EXCEPTION: main 
06-12 06:45:09.922: E/AndroidRuntime(6623): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.gw2legendary/com.example.gw2legendary.Bifrost}: java.lang.NullPointerException 
06-12 06:45:09.922: E/AndroidRuntime(6623): Caused by: java.lang.NullPointerException

The problem is that my activity crashes as soon as I try to open it with I add this code to it. The activity starts fine if I remove this code from it.

Upvotes: 0

Views: 2159

Answers (1)

dmon
dmon

Reputation: 30168

So the reason your code is failing: you declared your CheckBox variables as class fields, and they are initialized when the Activity starts, so the findViewById() returns null for all of them.

A quick fix: move all of those Checkbox declarations inside of your onClick method. Though it seems you might be using them somewhere else before the click.

A better potential solution: instead of trying to reference all of your 39 (!) checkboxes, it might be better to just get a reference to the container and iterate through all of the children, check if they are checkboxes and uncheck them if they are.

I will say that 39 checkboxes seems a bit ridiculous though.

Upvotes: 1

Related Questions