checking if a radio button is selected



i have a radio button group which contains 4 radio buttons none of them is checked by default



<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >

<RadioButton
android:id="@+id/ans11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/q"
android:text="RadioButton"
android:textColor="#747577"
android:textSize="35dp" />

<RadioButton
android:id="@+id/ans22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ans11"
android:text="RadioButton"
android:textColor="#747577"
android:textSize="35dp" />

<RadioButton
android:id="@+id/ans33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/memberexdone"
android:layout_below="@+id/ans22"
android:text="RadioButton"
android:textColor="#747577"
android:textSize="35dp" />

<RadioButton
android:id="@+id/ans44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/memberexdone"
android:layout_below="@+id/ans22"
android:text="RadioButton"
android:textColor="#747577"
android:textSize="35dp" />
</RadioGroup>


im trying to check if clicked on a button without selecting any of the radio buttons ..



rg = (RadioGroup) findViewById(R.id.radioGroup1);

// get selected radio button from radioGroup
int selectedId = rg.getCheckedRadioButtonId();

// find the radiobutton by returned id
rbtn = (RadioButton) findViewById(selectedId);

String selected = rbtn.getText().toString();
if (rg.getCheckedRadioButtonId() == -1)
{
//if the password less than 8 or more than 10
AlertDialog.Builder alertBuilder3=new AlertDialog.Builder(MemberExercise.this);
alertBuilder3.setTitle("Invalid");
alertBuilder3.setMessage("Please select an answer first, then click on done.");
alertBuilder3.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
dialog.cancel();


}
});

alertBuilder3.create().show();
}
else
{
.....
}


also tried if (rbtn.equals("")){}


but both when i click on the button without selecting any .. the application will stop ..why ?


No comments:

Post a Comment