Manju Manju - 12 days ago 5
Android Question

how to check all the CheckBox are checked on button Click in android

Below is the code where I am checking all the mandatory

CheckBox
is checked on NEXT button. There is totally 17 checkbox. But I am showing this in a Alert box so It is not taking this layout in View and taking the count of checked items in actual layout. Please help me to resolve this.

public void showConfirmPopup()
{
final Dialog dialog = new Dialog(SubmitViewActivity.this);
dialog.setContentView(R.layout.activity_uikyc);
dialog.setCancelable(false);
Button back=(Button)dialog.findViewById(R.id.btn_bck);
Button next=(Button)dialog.findViewById(R.id.btn_next);
final CheckBox[] checkboxes;
checkboxes = new CheckBox[17];

for(int i=0;i < checkboxes.length; i++){
checkboxes[i] = (CheckBox) findViewById(getIdName("check_" + (i+1)));
}

back.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.cancel();
}
});

next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
// TODO Auto-generated method stub
//int lenCheck = checkboxes.length;
int iCheck = 0;
for(int i=0;i<checkboxes.length;i++){

if(checkboxes[i].isChecked()){
iCheck++;
}

}
Log.e(String.valueOf(iCheck), "count of checked option");
if(iCheck != 17){
Toast.makeText(SubmitViewActivity.this, "Confirm all Checkboxes are checked" , Toast.LENGTH_LONG).show();
dialog.cancel();
}else if(iCheck == 17){
dialog.cancel();
savedetails = new SaveDetails();
savedetails.execute();
}
}
});

dialog.show();

}

Answer

Try this..

Change your CheckBox id in xml as check_1,check_2,check_3...check_17 like below for every 17

       <CheckBox
            android:id="@+id/check_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="check_1" />

and java

Declear as CheckBox[] checkboxs; in global variable and initilize it like below

    checkboxs = new CheckBox[17];

    for (int i = 0; i < checkboxs.length; i++) {
        checkboxs[i] = (CheckBox) findViewById(getIdByName("check_" + (i + 1)));
    }

getIdByName method

public static int getIdByName(final String name) {

     try {

         final Field field = R.id.class.getDeclaredField(name);

         field.setAccessible(true);
         return field.getInt(null);

     } catch (Exception ignore) {
         return -1;
     }
 }

and you can check wheather check box is checked or not using below codes.

    for (int i = 0; i < checkboxs.length; i++) {

        if(checkboxs[i].isChecked()){
              iCheck++;
        }
    }