Search code examples
javaandroidradio-buttonswitch-statementandroid-radiogroup

Changing the value of String in Switch statement in Java


I'm trying to change the value of a String data type inside a switch statement in Android. And that String is declared inside the same method in which the switch statement in declared, and I need to change the value of the String when the user click on the Radio Button.

public void CreateQuestion(View view) {

    String questionType = new String();
    RadioGroup questionTypeRadioGroup = (RadioGroup) findViewById(R.id.questionTypeRadioGroup);
    questionTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
                case R.id.true_false:
                    questionType = "True/False";
                    break;

                case R.id.mcqs:
                    questionType = "MCQs";
                    break;
            }
        }
    });
}

Solution

  • U should declare your string globally

    public class ExampleActivity extends AppCompatActivity {
        public String questionType;
    
        ....
    
        public void CreateQuestion(View view) {
             questionType = "";
             questionTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                  switch (checkedId) {
                         case R.id.true_false:
                              questionType = "True/False";
                              break;
    
                          case R.id.mcqs:
                              questionType = "MCQs";
                              break;
                        }
                    }
                });
            }
    
        ....
    
    }