Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Help in RadioButton Toast

enter image description here

If user clicks NEXT button without selecting option it has to toast a message, "pls select any one" else it should goto next screen. I have tried but its not going to next screen, Instead its showing toast"pls select any one" and my code

public class Question1 extends Activity implements OnClickListener {
Button vid, next;
Typeface tp;
TextView tv;
RadioGroup rg;
RadioButton rb;
Button b;
SharedPreferences sp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.question1);
    sp = getSharedPreferences("AppFile1", 0);

    tv = (TextView) findViewById(R.id.tvQuestion1);

    rg = (RadioGroup) findViewById(R.id.radioGroup1);
    vid = (Button) findViewById(R.id.buttonQuestion1VIdeo);
    next = (Button) findViewById(R.id.buttonQuestion1Next);
    vid.setOnClickListener(this);
    next.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.buttonQuestion1VIdeo:
        Intent i = new Intent(Question1.this, VideoActivity.class);
        startActivity(i);
        break;
    case R.id.buttonQuestion1Next:
        if (next.isSelected()) {
            int selectedId = rg.getCheckedRadioButtonId();
            rb = (RadioButton) findViewById(selectedId);
            String s = rb.getText().toString();
            SharedPreferences.Editor ed = sp.edit();
            ed.putString("q1", s);
            ed.commit();
            Intent ia = new Intent(Question1.this, Question2.class);
            startActivity(ia);

        } else {
            Toast.makeText(getApplicationContext(), "Please Select Answer", 0).show();
        }

        break;
    default:
        break;
    }

}

}

like image 558
DroidLearner Avatar asked Dec 27 '22 12:12

DroidLearner


1 Answers

Try with:

if (rg.getCheckedRadioButtonId()!=-1) {
        int selectedId = rg.getCheckedRadioButtonId();
        rb = (RadioButton) findViewById(selectedId);
        String s = rb.getText().toString();
        SharedPreferences.Editor ed = sp.edit();
        ed.putString("q1", s);
        ed.commit();
        Intent ia = new Intent(Question1.this, Question2.class);
        startActivity(ia);

    } else {
        Toast.makeText(getApplicationContext(), "Please Select Answer", 0).show();
    }

The documentation says that if no button is checked, getCheckedRadioButtonId() returns -1.

Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.

Therefore, if you have any value except -1 from that function, you have a selected button.

like image 194
Raghav Sood Avatar answered Jan 13 '23 08:01

Raghav Sood