My Activity has a RadioGroup with two Radio buttons and Save button which saves a value in String variable "type". First radio button will initialize type to "Fasting" and second button will initialize "type" to "Non fasting". If I select second option, type is not getting initialized. To make second button work, I have to select first button and click Save and then if I again select second option, then it will work. Here is the code.
diabetes_options.xml
<RadioGroup
android:id="@+id/do_radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/do_editText1"
android:visibility="visible" >
<RadioButton
android:id="@+id/do_fasting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fasting" />
<RadioButton
android:id="@+id/do_nonfasting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Non Fasting" />
</RadioGroup>
DiabetesOptions.java (inside onClick method for Save Button)
public class DiabetesOptions extends Activity {
int typeFlag=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
rGroup=(RadioGroup)findViewById(R.id.do_radioGroup1);
}
//This is the method invoked if we click Sabe button
public void onSave(View view) {
rGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.do_fasting:
type="Fasting";
typeFlag=1;
break;
case R.id.do_nonfasting:
type="Non Fasting";
typeFlag=1;
break;
}
}
});
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
date = dateFormat.format(new Date());
time = timeFormat.format(new Date());
try {
if(flag==1) {
DiabetesDatabase entry = new DiabetesDatabase(this);
if(typeFlag==1){
entry.createEntry(date,time,type,level);
Toast th = Toast.makeText(DiabetesOptions.this, "Entry Saved", Toast.LENGTH_SHORT);
th.show();
}
else if(typeFlag==0){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(DiabetesOptions.this);
alertDialog.setTitle("Alert!!!");
alertDialog.setMessage("Select FASTING or NON FASTING option");
alertDialog.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}