Hello to everyone i am creating a quiz app in which I am creating a dynamic UI for multiple choice question it Works well but when i select radio button on question and then go for next question and select the radio button i gives me error "java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton" Also when i change the selected option Example : First i choose option 1 of a question and then i change it to Option 2 it give me the same error Here is the sample of my code
for(int i=1;i<=5;i++){
TextView tv=new TextView(this);
tv.setId(i);
RadioGroup radioGroup=new RadioGroup(this);
for(int j=0;j<=3;j++){
RadioButton b1=new RadioButton(this);
b1.setText("option"+j);
b1.setId(j);
radioGroup.addView(b1);
}
tv.setText("Youre question No "+i);
tv.setTypeface(null, Typeface.BOLD);
tv.setTextColor(Color.BLACK);
radioGroup.setOrientation(RadioGroup.VERTICAL);
tv.setPadding(20,0,0,0);
radioGroup.setPadding(0,5,0,0);
linearLayout.addView(tv);
linearLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(this);
}
}
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if (radioGroup.getCheckedRadioButtonId() != -1) {
RadioButton uans = findViewById(radioGroup.getCheckedRadioButtonId());//Error occurred here
String ansText = uans.getText().toString();
answersStringArray.add(ansText);
}
}
Here is the Exception :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizapp, PID: 3428
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton
at com.example.quizapp.Paper.onCheckedChanged(Paper.java:99)//This shows where is the error
at android.widget.RadioGroup.setCheckedId(RadioGroup.java:196)
at android.widget.RadioGroup.access$600(RadioGroup.java:59)
at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:381)
at android.widget.CompoundButton.setChecked(CompoundButton.java:183)
at android.widget.CompoundButton.toggle(CompoundButton.java:135)
at android.widget.RadioButton.toggle(RadioButton.java:76)
at android.widget.CompoundButton.performClick(CompoundButton.java:140)
at android.view.View.performClickInternal(View.java:7218)
at android.view.View.access$3800(View.java:824)
at android.view.View$PerformClick.run(View.java:27719)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
How can i overcome this please help me guys thanks in advance