Showing text from string through TextView after pressing RadioButton - java

I'm trying to show automaticly "This is the correct answer" or "Try again" just right after the radio button is pressed.
My question is:
How to add two strings
<string name="Good_answer">That is the correct answer</string>
<string name="Wrong_answer">Try again</string>
to this textView
<TextView
android:id="#+id/textViewAnswer"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAlignment="center"
android:layout_below="#id/rg2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
so I can proceed this
for (boolean radioAnswer : answer)
correct = correct && radioAnswer;
if (correct)
tv.setText(R.string.Good_answer);
else
tv.setText(R.string.Wrong_answer);
And here is setOnClick... (at first it was with checkbutton 'mbuton')
mbuton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean check = true;
boolean correct = true;
// To check if all questions have been answered
for (boolean radioChecked : checked)
check = check && radioChecked;
if (check) {
// To check if all questions have been answered correctly
for (boolean radioAnswer : answer)
correct = correct && radioAnswer;
if (correct)
tv.setText(R.string.Good_answer);
else
tv.setText(R.string.Wrong_answer);
}
else
tv.setText("Answer all questions");
}
});
Xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RadioGroup
android:id="#+id/rg1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question 1"/>
<RadioButton
android:text="Correct Option"
android:id="#+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
<RadioGroup
android:layout_marginTop="16dp"
android:layout_below="#+id/rg1"
android:id="#+id/rg2"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question 2"/>
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Correct Option"
android:id="#+id/radioButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
<TextView
android:id="#+id/textViewAnswer"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAlignment="center"
android:layout_below="#id/rg2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
And string
<string name="Good_answer">That is the correct answer</string>
<string name="Wrong_answer">Try again</string>

// i have modified your code, please check it.
// i have display message if user does not select any radio button,
//another wise it display correct answer count on textview.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class Main2Activity2 extends Activity {
TextView tv;
Button mbuton;
RadioGroup rg1,rg2;
ArrayList<Integer> arrayListOfRadioGroupId =new ArrayList<Integer>();
int noAnswerCount= 0;
int correctAnswerRadioButtonCount= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textViewAnswer);
mbuton = (Button) findViewById(R.id.mbuton);
rg1 = (RadioGroup)findViewById(R.id.rg1);
rg2 = (RadioGroup)findViewById(R.id.rg2);
// Store Radio group id to arraylist
arrayListOfRadioGroupId.add(rg1.getId());
arrayListOfRadioGroupId.add(rg2.getId());
mbuton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noAnswerCount= 0;
correctAnswerRadioButtonCount= 0;
for(int radioGroupId: arrayListOfRadioGroupId)
{
RadioGroup objRadioGroup = (RadioGroup) findViewById(radioGroupId);
int checkedId=objRadioGroup.getCheckedRadioButtonId();
// get Selected Radio button id.
if(checkedId>-1) {
RadioButton rB = (RadioButton) findViewById(checkedId);
String strRadioButtonText = rB.getText().toString();
// get Selected Radio button Text.
if(strRadioButtonText.equals("Correct Option"))
{
correctAnswerRadioButtonCount ++;
noAnswerCount --;
}
}
else
{
noAnswerCount++;
}
}
if(noAnswerCount > 0)
{
tv.setText("Answer all questions");
}
else
{
tv.setText("Correct Answer Count is: " +correctAnswerRadioButtonCount);
}
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radioButton5) {
RadioButton rB = (RadioButton) findViewById(checkedId);
String strRadioButtonText = rB.getText().toString();
// get Selected Radio button Text.
if(strRadioButtonText.equals("Correct Option")) {
tv.setText("Correct Answer");
}
else
{
tv.setText("Wrong Answer");
}
}
}
});
}
}
// my Xml code is.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RadioGroup
android:id="#+id/rg1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question 1"/>
<RadioButton
android:text="Correct Option"
android:id="#+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
<RadioGroup
android:layout_marginTop="16dp"
android:layout_below="#+id/rg1"
android:id="#+id/rg2"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question 2"/>
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Correct Option"
android:id="#+id/radioButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="Wrong Option"
android:id="#+id/radioButton6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
<TextView
android:id="#+id/textViewAnswer"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAlignment="center"
android:layout_below="#id/rg2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/mbuton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MButton"
android:layout_below="#id/textViewAnswer"/>
</RelativeLayout>

If your problem is just about setting those string in the TextView then, try this:
//For correct answer.
String CorrectAnswer = getString(R.string.Good_answer);
tv.setText(CorrectAnswer);
//For wrong answer.
String WrongAnswer = getString(R.string.Wrong_answer);
tv.setText(WrongAnswer);

The Code is still unclear (I can't Figure out what mButton is) .
However can you also share your layout xml I would suggest having a Radio Group comprising of X number of Radio Buttons (options) that you like and put the on checkedChangeListener
<RadioGroup
android:id="#+id/rgroup"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:background="#drawable/background"
android:gravity="center"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/option1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#drawable/test_image"
android:button="#null" />
<RadioButton
android:id="#+id/option2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#drawable/test_image"
android:button="#null" />
</RadioGroup>
Your Activity should implement the OnCheckedChangeListener and you can then define your Radio Group RadioGroup Options = (RadioGroup) findViewById(R.id.rgroup);
Then you can implement a method in your activity where if a option inside that Radio Button is clicked you can use the below method.
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId)
{
switch (checkedId)
{
case R.id.option1:
// settextview to correct here
break;
case R.id.option2:
//set textview to wrong here
break;
default:
break;
}
}
Assuming you might have answers at dynamic positions you might want to code some logic in the on checked change method . Hope this helps

Layout file; look at those questions and answers. I've hardcoded the string here. You can set it in string resource file and fetch it here using #string or set it dynamically using yourTextView.setText() method.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RadioGroup
android:id="#+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is your name?"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black" />
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Melisa" />
<RadioButton
android:id="#+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alisha" />
<RadioButton
android:id="#+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lolita" />
</RadioGroup>
<RadioGroup
android:id="#+id/rg2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rg1"
android:layout_marginTop="16dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What are you learning?"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black" />
<RadioButton
android:id="#+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C++" />
<RadioButton
android:id="#+id/radioButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />
<RadioButton
android:id="#+id/radioButton6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HTML" />
</RadioGroup>
<TextView
android:id="#+id/textViewAnswer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/rg2"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
And in your activity.
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroupFirst, radioGroupSecond;
private String[] realAnswers = {"Melisa", "Android"};
private String[] userAnswers;
private TextView tv;
private boolean status = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroupFirst = (RadioGroup) findViewById(R.id.rg1);
radioGroupSecond = (RadioGroup) findViewById(R.id.rg2);
tv = (TextView) findViewById(R.id.textViewAnswer);
userAnswers = new String[2];
radioGroupFirst.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
tv.setText("");
RadioButton nameRadio = (RadioButton) findViewById(checkedId);
Log.e("ID", "" + nameRadio.getText().toString());
userAnswers[0] = nameRadio.getText().toString();
}
});
radioGroupSecond.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton learningRadio = (RadioButton) findViewById(checkedId);
Log.e("ID", "" + learningRadio.getText().toString());
userAnswers[1] = learningRadio.getText().toString();
if (checkStatus(userAnswers))
tv.setText(getString(R.string.Good_answer));
else
tv.setText(getString(R.string.Wrong_answer));
}
});
}
private boolean checkStatus(String[] userAnswers) {
status = true;
for (int i = 0; i < userAnswers.length; i++) {
Log.e(userAnswers[i], realAnswers[i]);
if (!userAnswers[i].equals(realAnswers[i]))
status = false;
}
return status;
}
}
I haven't use the string resources here, if you want to set the text view with the string from resources too, look it in my first answer.
So, I think this will help you.

Related

How do I change layout view on the application when i have multiple separate layouts(screens)?

xml mainactivity screen 1
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#00008b"
android:id="#+id/page"
>
<TextView
android:id="#+id/game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The Random Game"
android:textStyle="bold|italic"
android:layout_centerInParent="true"
android:layout_alignParentTop="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:textColor="#006400"
android:outlineSpotShadowColor="#2196F3"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonstart"
android:text="Start"
android:textStyle="bold|italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/game"
android:layout_centerInParent="true"
android:textColor="#006400"
android:background="#8b0000"
/>
<TextView
android:id="#+id/TVshowmessage"
android:text="the number is"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonstart"
android:layout_centerInParent="true"
android:textColor="#006400"
/>
<Button
android:id="#+id/buttonplus"
android:text="+"
android:textStyle="bold|italic"
android:textSize="#android:dimen/app_icon_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TVshowmessage"
android:layout_centerInParent="true"
android:textColor="#006400"
android:background="#8b0000"
/>
<TextView
android:id="#+id/TVcurrentnum"
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonplus"
android:layout_centerInParent="true"
android:textColor="#006400"
android:background="#8b0000"
/>
<Button
android:id="#+id/buttonminus"
android:text="-"
android:textSize="#android:dimen/app_icon_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TVcurrentnum"
android:layout_centerInParent="true"
android:textColor="#006400"
android:background="#8b0000"
/>
<TextView
android:id="#+id/tvcounter"
android:text="counter"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:layout_centerInParent="true"
android:layout_marginBottom="300dp"
android:background="#8b0000"
android:textColor="#006400"
android:textStyle="bold|italic"
android:textAlignment="center"
android:layout_below="#id/buttonrestart"
/>
<Button
android:id="#+id/buttoncheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:textColor="#006400"
android:background="#8b0000"
android:textStyle="bold|italic"
android:outlineSpotShadowColor="#008B02"
android:text="Check"
android:layout_below="#id/buttonminus"
/>
<Button
android:id="#+id/buttonrestart"
android:text="restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#006400"
android:background="#8b0000"
android:textStyle="bold|italic"
android:layout_below="#id/buttoncheck"
/>
</RelativeLayout>
foundnum xml screen 2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00008b"
android:id="#+id/grats"
>
<TextView
android:id="#+id/tvfound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="congrats"
android:textColor="#006400"
android:background="#8b0000"
android:textStyle="bold|italic"
android:layout_above="#+id/buttonrestart1"
android:layout_centerInParent="true"
/>
<Button
android:id="#+id/buttonrestart1"
android:text="restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#006400"
android:background="#8b0000"
android:textStyle="bold|italic"
/>
</RelativeLayout>
main activity java.
package com.example.findrandomnumber;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonstart, buttonplus, buttonminus, buttoncheck, buttonrestart,buttonrestart1;
private TextView TVcurrentnum, TVshowmessage, tvcounter,tvfoundnum;
private String TAG = "gilog",currentnum,counter;
private Controllerguessnum myC;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: hi");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonstart =(Button) findViewById(R.id.buttonstart);
buttonplus = (Button)findViewById(R.id.buttonplus);
buttonminus =(Button) findViewById(R.id.buttonminus);
buttoncheck = (Button)findViewById(R.id.buttoncheck);
buttonrestart = (Button)findViewById(R.id.buttonrestart);
buttonrestart1 = (Button)findViewById(R.id.buttonrestart1);
TextView tvcounter= findViewById(R.id.tvcounter);
TextView TVshowmessage= findViewById(R.id.TVshowmessage);
TextView TVcurrentnum= findViewById(R.id.TVcurrentnum);
TextView tvfoundnum= findViewById(R.id.tvfound);
findViewById(R.id.page);
findViewById(R.id.grats);
buttonstart.setOnClickListener(this);
buttonrestart.setOnClickListener(this);
buttoncheck.setOnClickListener(this);
buttonplus.setOnClickListener(this);
buttonminus.setOnClickListener(this);
Log.d(TAG, "onCreate: set clickers worked");
}
public void startGame() {
myC = new Controllerguessnum();
Log.d(TAG, "startGame: random number is " + myC.crandom());
}
public void showmessage(){
TextView TVshowmessage= findViewById(R.id.TVshowmessage);
Log.d(TAG, "onClick: button check was pressed");
if (myC.ccheck() == "smaller"){
Log.d(TAG, "onClick: check is ? "+ myC.ccheck() +" numbers: "+myC.ccurrentnum()+ "<"+ myC.crandom());
TVshowmessage.setText("number is smaller than random number" + 0);
}
else
if (myC.ccheck() == "equal"){
Log.d(TAG, "onClick: check is ? "+ myC.ccheck() + "="+ myC.crandom());
TVshowmessage.setText("congrats you found the number, "+String.valueOf(myC.ccounter()/2)+" tries,"+ " press restart to play again" );
}
else {
if(myC.ccheck() == "bigger") {
Log.d(TAG, "onClick: check is ? "+ myC.ccheck() + ">"+ myC.crandom());
TVshowmessage.setText("number you chose is bigger than random number" + 0);
}
}
}
public void changepage(){
TextView tvfoundnum= findViewById(R.id.tvfound);
RelativeLayout grats= findViewById(R.id.grats);
RelativeLayout page= findViewById(R.id.page);
TextView TVshowmessage= findViewById(R.id.TVshowmessage);
if (myC.ccheck() == "equal"){
page.setVisibility(View.GONE);
setContentView(grats);
}
else{
setContentView(page);
}
}
#Override
public void onClick(View v) {
buttonstart =(Button) findViewById(R.id.buttonstart);
buttonplus = (Button)findViewById(R.id.buttonplus);
buttonminus =(Button) findViewById(R.id.buttonminus);
buttoncheck = (Button)findViewById(R.id.buttoncheck);
buttonrestart = (Button)findViewById(R.id.buttonrestart);
TVcurrentnum= findViewById(R.id.TVcurrentnum);
tvcounter= findViewById(R.id.tvcounter);
if (v.getId() == R.id.buttonstart || v.getId() == R.id.buttonrestart) {
startGame();
}
if (v.getId() == R.id.buttonrestart1){
findViewById(R.id.page).setVisibility(View.VISIBLE);
findViewById(R.id.grats).setVisibility(View.GONE);
startGame();
}
//button check
if (v.getId() == R.id.buttoncheck) {
showmessage();
myC.ccntplus();
tvcounter.setText(String.valueOf((int)(myC.ccounter())+ 0));
Log.d(TAG, "onClick: counter returned"+ tvcounter.getText());
changepage();
}
if (v.getId() == R.id.buttonplus) {
Log.d(TAG, "onClick: button plus was pressed");
myC.cplus();
TVcurrentnum.setText(String.valueOf((int)(myC.ccurrentnum()) + 0));
} else if (v.getId() == R.id.buttonminus) {
Log.d(TAG, "onClick: button minus was pressed");
myC.cminus();
TVcurrentnum.setText(String.valueOf((int)(myC.ccurrentnum()) + 0));
}
}
}
there is more code in two other java files but these are not relevant to changing screen but I will add it below.
controller.java
package com.example.findrandomnumber;
public class Controllerguessnum {
private Modelguessnum myModel1;
public double counter=0;
private int random;
public Controllerguessnum(){
myModel1= new Modelguessnum();
cstartGame();
this.counter=0;
}
public void cstartGame(){
myModel1.mStartGame();
this.counter=0; }
public void crestartgame(){
myModel1.mStartGame();
this.counter=0;
}
public void cplus(){
myModel1.mplus();
}
public void cminus(){
myModel1.mminus();
}
public void ccntplus(){
this.counter++;
}
public String ccheck(){
String res = myModel1.mcheck();
return res;
}
public double ccurrentnum(){
int cnum=myModel1.getCurrentnum();
return cnum;
}
public double ccounter(){
double cnt= this.counter;
return cnt;
}
public int crandom(){
this.random = myModel1.getRandomnum();
return this.random;
}
}
model.java
package com.example.findrandomnumber;
import java.util.Random;
public class Modelguessnum {
private int currentnum;
private int randomnum;
private int counter=0;
public Modelguessnum() {
}
public void mStartGame(){
// this.randomnum= new Random().nextInt( 100);
// this.currentnum= new Random().nextInt(100);
this.randomnum=5;
this.currentnum=5;
}
public int getCurrentnum(){
int mnum= currentnum;
return mnum;
}
public int getRandomnum(){
return randomnum;
}
public void mplus(){
this.currentnum++;
}
public void mminus()
{
this.currentnum--;
}
public String mcheck() {
//-1 is smaller
//0 equal
//1 is bigger
if (this.currentnum > this.randomnum) {
return "bigger";
}
else
if (this.currentnum==this.randomnum){
return "equal";
}
else
if(this.currentnum < this.randomnum){
return "smaller";
}
else
return "neither";
}
}
the math part of the code worked fine- any improvements are welcome. - how do I solve the errors so that when I find the number, when the random number = current number and when I press check, I want it to bring me to the second screen/layout(foundnum.xml) - foundnum.xml
the error I get from this is the following:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.findrandomnumber, PID: 480
java.lang.IllegalArgumentException: Cannot add a null child view to a ViewGroup
at android.view.ViewGroup.addView(ViewGroup.java:3718)
at android.view.ViewGroup.addView(ViewGroup.java:3700)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:687)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:175)
at com.example.findrandomnumber.MainActivity.changepage(MainActivity.java:95)
at com.example.findrandomnumber.MainActivity.onClick(MainActivity.java:129)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)>
The exception you getting is that you: Cannot add a null child view to a ViewGroup.
A ViewGroup is a view that can contain other views. The ViewGroup is the base class for Layouts in android, like LinearLayout , RelativeLayout , FrameLayout etc. In other words, ViewGroup is generally used to define the layout in which views(widgets) will be set/arranged/listed on the android screen.
You have two ViewGroups: one activity_main.xml and foundnum.xml
Within your code (MainActivity), you set activity_main.xml as your viewGroup by this line of code setContentView(R.layout.activity_main); in your oncreate method.
What causes the error??
The error is caused by taking action(setting text or setting onclick action) on tvfoundnum and buttonrestart1:
TextView tvfoundnum= findViewById(R.id.tvfound)
buttonrestart1 = (Button)findViewById(R.id.buttonrestart1);
Any action you set to them will result into an error because those views are not part of the set ViewGroup. In otherwards they are not contained in activity_main.xml and they are not yet known
Solution Options:
There are 2 ways you can be able to achieve what you want:
By hiding and displaying only the views you want to display: Meaning you will have to combine foundnum.xml's code to activity_main.xml. Such that you have one layout.
By using fragments. With fragments, you can have one fragment manage more than one ViewGroup (layouts).
Since you are using activity, I will demonstrate solution option (1) bellow
Solution Option One.
This is the new layout(it contains code from activity_main.xml & foundnum.xml): activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<RelativeLayout
android:id="#+id/page"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:outlineSpotShadowColor="#2196F3"
android:text="The Random Game"
android:textColor="#006400"
android:textStyle="bold|italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<Button
android:id="#+id/buttonstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/game"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="Start"
android:textColor="#006400"
android:textStyle="bold|italic"
/>
<TextView
android:id="#+id/TVshowmessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonstart"
android:layout_centerInParent="true"
android:text="the number is"
android:textColor="#006400"
/>
<Button
android:id="#+id/buttonplus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TVshowmessage"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="+"
android:textColor="#006400"
android:textSize="#android:dimen/app_icon_size"
android:textStyle="bold|italic"
/>
<TextView
android:id="#+id/TVcurrentnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonplus"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="0"
android:textColor="#006400"
/>
<Button
android:id="#+id/buttonminus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TVcurrentnum"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="-"
android:textColor="#006400"
android:textSize="#android:dimen/app_icon_size"
/>
<TextView
android:id="#+id/tvcounter"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:layout_below="#id/buttonrestart"
android:layout_centerInParent="true"
android:layout_marginBottom="300dp"
android:background="#8b0000"
android:text="counter"
android:textAlignment="center"
android:textColor="#006400"
android:textStyle="bold|italic"
/>
<Button
android:id="#+id/buttoncheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonminus"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:background="#8b0000"
android:outlineSpotShadowColor="#008B02"
android:text="Check"
android:textColor="#006400"
android:textStyle="bold|italic"
/>
<Button
android:id="#+id/buttonrestart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttoncheck"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="restart"
android:textColor="#006400"
android:textStyle="bold|italic"
/>
</RelativeLayout>
<!-- code from foundnm.xml-->
<RelativeLayout
android:id="#+id/grats"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
>
<TextView
android:id="#+id/tvfound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonrestart1"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="congrats"
android:textColor="#006400"
android:textStyle="bold|italic"
/>
<Button
android:id="#+id/buttonrestart1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#8b0000"
android:text="restart"
android:textColor="#006400"
android:textStyle="bold|italic"
/>
</RelativeLayout>
</RelativeLayout>
Note that, when you run the app take note that some views are hidden, that is
<RelativeLayout>
<!--page relative layout--> This is visible (visibilty = visible )
<!--grats relative layout--> This is invisible (visibility = gone)
</RelativeLayout>
After doing whatever its that you want to do(checking if number is in the counter.....), set visible to <!--grats relative layout--> and set visibility gone for <!--page relative layout-->
You need to modify the the if statement in this function: changepage(), to something like this
public void changepage(){
if (myC.ccheck() == "equal"){
page.setVisibility(View.GONE);
grats.setVisibility(View.VISIBLE);
}
else{
grats.setVisibility(View.GONE);
page.setVisibility(View.VISIBLE);
}
}
I hope you find this helpful. If you have issues, please comment, I will help you out.

Reset results and TextUtil

So, I got a feedback from reviewer and fixed most of my problems but there are two problems that I can’t find solution (I will use bold font to highlight them) the first problem comes after I click result button more than one time because the previous result is added. I know that I should add all the methods checkQuestionOne to checkQuestion6 in the button method but this is not possible so far because the method needs (View or view value) which is not working and I don’t know why so I decided not to include the four Radio buttons methods in it. Second when the checkQuestionFive is blank or there is no value the app crashes I was told to use if (!TextUtils.isEmpty(gettingQuestionFive.getText())), then I add Toast message into the if statement but it still crashes. Any help will be appreciated!!
Thank you!
Java code:
public class MainActivity extends AppCompatActivity {
int health = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkQuestionOne(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_one_yes:
if (checked)
health += 1;
break;
}
}
public void checkQuestionTwo(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_two_yes:
if (checked)
health ++;
break;
}
}
public void checkQuestionThree(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_three_no:
if (checked)
health ++;
break;
}
}
public void checkQuestionFour(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_four_no:
if (checked)
health ++;
break;
}
}
**public void checkQuestionFive**() {
EditText gettingQuestionFive = findViewById(R.id.sleep_hours);
if (!TextUtils.isEmpty(gettingQuestionFive.getText())){
Toast displayError = Toast.makeText(this, "You missed question 5, plase don't leave it blank", Toast.LENGTH_LONG);
displayError.show();
}
int answerQuestionFive = Integer.parseInt(gettingQuestionFive.getText().toString());
if (answerQuestionFive >= 7) {
health ++;
}
}
public void checkQuestionSix() {
CheckBox checkBoxOneA = findViewById(R.id.fruits_check_box);
CheckBox checkBoxOneB = findViewById(R.id.chips_check_box);
CheckBox checkBoxOneC = findViewById(R.id.candy_check_box);
CheckBox checkBoxOneD = findViewById(R.id.all_three_check_box);
if (checkBoxOneA.isChecked() && !checkBoxOneB.isChecked() && !checkBoxOneC.isChecked() && !checkBoxOneD.isChecked()) {
health++;
}
}
**public void overView(View view)**{
checkQuestionFive();
checkQuestionSix();
Toast displayToast = Toast.makeText(this, health + " is your score. If is 4 or above, you have a healthy life", Toast.LENGTH_LONG);
displayToast.show();
health = 0;
}
}
XML code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.martinevtimov.quizapp2.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/group1" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1. Do you eat healty?"
android:textSize="30sp"
android:textStyle="bold" />
<RadioButton
android:id="#+id/question_one_yes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Yes"
android:onClick="checkQuestionOne" />
<RadioButton
android:id="#+id/question_one_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No"
android:onClick="checkQuestionOne" />
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/group2" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2. Do you work out?"
android:textSize="30sp"
android:textStyle="bold" />
<RadioButton
android:id="#+id/question_two_yes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Yes"
android:onClick="checkQuestionTwo" />
<RadioButton
android:id="#+id/question_two_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No"
android:onClick="checkQuestionTwo" />
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/group3" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="3. Do you drink?"
android:textSize="30sp"
android:textStyle="bold" />
<RadioButton
android:id="#+id/question_three_yes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Yes"
android:onClick="checkQuestionThree" />
<RadioButton
android:id="#+id/question_three_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No"
android:onClick="checkQuestionThree" />
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/group4" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="4. Do you smoke?"
android:textSize="30sp"
android:textStyle="bold" />
<RadioButton
android:id="#+id/question_four_yes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Yes"
android:onClick="checkQuestionFour" />
<RadioButton
android:id="#+id/question_four_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No"
android:onClick="checkQuestionFour" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="5. How many hours do you sleep?"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="#+id/sleep_hours"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type here"
android:inputType="number" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="6. What is a healthy snack?"
android:textSize="30sp"
android:textStyle="bold" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fruits"
android:id="#+id/fruits_check_box" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Chips"
android:id="#+id/chips_check_box" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Candy"
android:id="#+id/candy_check_box" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="All three"
android:id="#+id/all_three_check_box" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="overView"
android:text="Check my health"
android:textAllCaps="true" />
</LinearLayout>
</ScrollView>
You can see the Logcat and the message error I have. The purpose of this app is to make a quiz app with 3 different inputs (EditText, Radio Buttons, and CheckBoxes). When the EditText is left blank, a crash appears. It seems there is some problem with the onClick attribute in your code but I can figure it out. The second problem comes from clicking the check button more than one time than more points are added to the previous points, I tried to add all the question methods into one and then set the global health variable to 0 but is not really working. Also, take a look of the two pictures below my code.
Screen Picture 1
Screen Picture 2

How do i ensure that the selection of a radio button from a radio group affects the selection of a radio button in a different radio group.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="24dp"
android:text="1. Do you have an anti-virus installed on your computer :"
android:textAllCaps="false" />
<RadioGroup
android:id="#+id/radio_virus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="48dp">
<RadioButton
android:id="#+id/radio_virusyes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:onClick="assessUserInput"
android:text="Yes" />
<RadioButton
android:id="#+id/radio_virusno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="assessUserInput"
android:text="No" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="48dp"
android:text="If No, skip question 2"
android:textAllCaps="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:text="2. How many anti-viruses do you use on your laptop :"
android:textAllCaps="false" />
<RadioGroup
android:id="#+id/radio_avnumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="48dp">
<RadioButton
android:id="#+id/radio_avnumberone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="assessUserInput"
android:text="1" />
<RadioButton
android:id="#+id/radio_avnumbermore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="assessUserInput"
android:text="More than 1" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="24dp"
android:text="3. Do you use pop-up/advert blockers:"
android:textAllCaps="false" />
<RadioGroup
android:id="#+id/radio_adblock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="48dp">
<RadioButton
android:id="#+id/radio_adblockyes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:onClick="assessUserInput"
android:text="Yes" />
<RadioButton
android:id="#+id/radio_adblockno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="assessUserInput"
android:text="No" />
</RadioGroup>
Instead of writing text to guide a user to skip question 2 after he
selects "No" in question 1, i want to be able to find a way to disable question two using java or xml codes when the user selects a "No". or automatically take question two away.
Activity:
(Note:i dont know why you want the strings so i separated them from the disabling method but with this it will disable the radio buttons if the user pressed no and they will enable when the user presses yes)
public class main extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainz);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_virus);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioGroup rg1 = (RadioGroup) findViewById(R.id.radio_avnumber);
Log.w("","click!");
if (checkedId == R.id.radio_virusno) {
Log.w("","asdasda");
for (int i = 0; i < rg1.getChildCount(); i++) {
rg1.getChildAt(i).setEnabled(false);
}
}else
{
Log.w("","else");
for (int i = 0; i < rg1.getChildCount(); i++) {
rg1.getChildAt(i).setEnabled(true);
}
}
}
});
}
public void assessUserInput(View view){
//// constructor method for Radio Group : Radio_virus
RadioGroup rgVirus=(RadioGroup)findViewById(R.id.radio_virus);
String radioVirus=((RadioButton)findViewById(rgVirus.getCheckedRadioButtonId())).getText().toString();
//// constructor method for Radio Group : Radio_avnumber
RadioGroup rgAvnNumber=(RadioGroup)findViewById(R.id.radio_avnumber);
String radioAvNumber=((RadioButton)findViewById(rgAvnNumber.getCheckedRadioButtonId())).getText().toString();
/// constructor method for Radio Group : Radio_adblock
RadioGroup rgAdBlock=(RadioGroup)findViewById(R.id.radio_adblock);
String radioAdBlock=((RadioButton)findViewById(rgAdBlock.getCheckedRadioButtonId())).getText().toString();
// constructor method for Input field
//EditText nameTextField=(EditText)findViewById(R.id.edit_name);
//String hasName=nameTextField.getText().toString();
}
}
Used xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="24dp"
android:text="1. Do you have an anti-virus installed on your computer :"
android:textAllCaps="false" />
<RadioGroup
android:id="#+id/radio_virus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="48dp">
<RadioButton
android:id="#+id/radio_virusyes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Yes" />
<RadioButton
android:id="#+id/radio_virusno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="48dp"
android:text="If No, skip question 2"
android:textAllCaps="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:text="2. How many anti-viruses do you use on your laptop :"
android:textAllCaps="false" />
<RadioGroup
android:id="#+id/radio_avnumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="48dp">
<RadioButton
android:id="#+id/radio_avnumberone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<RadioButton
android:id="#+id/radio_avnumbermore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="More than 1" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="24dp"
android:text="3. Do you use pop-up/advert blockers:"
android:textAllCaps="false" />
<RadioGroup
android:id="#+id/radio_adblock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="48dp">
<RadioButton
android:id="#+id/radio_adblockyes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Yes" />
<RadioButton
android:id="#+id/radio_adblockno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No" />
</RadioGroup>
</LinearLayout>
You have to handle onClick of your radiobutton :
public void assessUserInput(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_virusyes:
if (checked){
for(int i = 0; i < radio_avnumber.getChildCount(); i++){
((RadioButton)radio_avnumber.getChildAt(i)).setEnabled(true);}}
break;
case R.id.radio_virusno:
if (checked){
for(int i = 0; i < radio_avnumber.getChildCount(); i++){
((RadioButton)radio_avnumber.getChildAt(i)).setEnabled(false);}
}
break;
}
}
public void assessUserInput(View view) {
//// constructor method for Radio Group : Radio_virus
RadioGroup rgVirus = (RadioGroup) findViewById(R.id.radio_virus);
String radioVirus = ((RadioButton) findViewById(rgVirus.getCheckedRadioButtonId())).getText().toString();
//// constructor method for Radio Group : Radio_avnumber
RadioGroup rgAvnNumber = (RadioGroup) findViewById(R.id.radio_avnumber);
String radioAvNumber = ((RadioButton) findViewById(rgAvnNumber.getCheckedRadioButtonId())).getText().toString();
/// constructor method for Radio Group : Radio_adblock
RadioGroup rgAdBlock = (RadioGroup) findViewById(R.id.radio_adblock);
String radioAdBlock = ((RadioButton) findViewById(rgAdBlock.getCheckedRadioButtonId())).getText().toString();
// constructor method for Input field
EditText nameTextField = (EditText) findViewById(R.id.edit_name);
String hasName = nameTextField.getText().toString();
// Is the button now checked
radioVirus.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId = radio_virusno) {
//set the style of the things you want to disable here
}
}
});

Android code error. Application stops unexpectedly

I'm having a problem with my code. Whenever I run it, it shows the error error application stopped unexpectedly. I think the issue is caused by some error in the Java class. What exactly is causing this issue?
Here is my XML file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:padding="10dp"
android:overScrollMode="always"
android:layout_height="match_parent"
android:background="#A52A2A"
tools:context="com.safeermalik.gpa.Start">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="Subject :"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Subject Name"
android:id="#+id/subject"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="Marks :"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Subject Marks"
android:id="#+id/marks"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="Credits :"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Subject Credits"
android:id="#+id/credits"/>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="Criteria :"/>
<RadioButton android:id="#+id/radio_old"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Old Criteria"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_new"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Criteria"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:padding="5dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add course"
android:background="#696969"
android:id="#+id/add"
android:onClick="sendMessage"/>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/add_table"
>
<TableRow
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:textStyle="bold"
android:textSize="18sp"
android:text="Subject "/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:textStyle="bold"
android:textSize="18sp"
android:text="Marks "/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:textStyle="bold"
android:textSize="18sp"
android:text="Credits "/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:textStyle="bold"
android:textSize="18sp"
android:text="Percentage "/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:textStyle="bold"
android:textSize="18sp"
android:text="GPA "/>
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="Total Marks : "/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/total_marks"
android:hint="Total Marks "/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="S-GPA : "/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/s_gpa"
android:hint="GPA "/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:text="PERCENTAGE : "/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/final_percentage"
android:hint="Percentage "/>
</TableRow>
</TableLayout>
</LinearLayout>
Here is the Java class:
public class Start extends ActionBarActivity {
EditText sub;
EditText mark;
EditText credit;
Button Adds;
int a=0,b=0,hour=0,x=0,counter=0;
String grade="";
String subject="";
EditText SUM,percent,GPA;
double gpa,gpa_multiple;
TableLayout table;
CalcGPA cal=new CalcGPA();
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio_new:
if (checked)
x=1;
break;
case R.id.radio_old:
if (checked)
x=0;
break;
} }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
sub=(EditText)findViewById(R.id.subject);
subject=sub.getText().toString();
mark=(EditText)findViewById(R.id.marks);
a=Integer.parseInt(String.valueOf(mark));
credit=(EditText)findViewById(R.id.credits);
b=Integer.parseInt(String.valueOf(credit));
Adds=(Button)findViewById(R.id.add);
table=(TableLayout)findViewById(R.id.add_table);
SUM=(EditText)findViewById(R.id.total_marks);
GPA=(EditText)findViewById(R.id.s_gpa);
percent=(EditText)findViewById(R.id.final_percentage);
Adds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sub.setText("");
mark.setText("");
credit.setText("");
counter++;
hour +=b;
if(x==0){
gpa=cal.subgpa(a);
grade=cal.Grade(a);
}
else if(x==1){
gpa=cal.ChangedGpa(a);
grade=cal.ChangedGrade(a);
}
add_row(subject,a,b,gpa,grade);
gpa_multiple+=(gpa*b);
SUM.setText(""+(counter*a));
GPA.setText(""+(gpa_multiple/hour));
percent.setText(""+((counter*a)/(counter*100)*100));
}
} );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void add_row(String sub, int crdt, int marks, double sgpa, String subgrade ){
TableLayout tb = (TableLayout) findViewById(R.id.add_table);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView subject_name=new TextView(this);
subject_name.setText(counter+""+sub);
subject_name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
subject_name.setBackgroundResource(R.drawable.border);
TextView subject_marks=new TextView(this);
subject_marks.setText(""+marks);
subject_marks.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
subject_marks.setBackgroundResource(R.drawable.border);
TextView subject_credits=new TextView(this);
subject_credits.setText(""+crdt);
subject_credits.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
subject_credits.setBackgroundResource(R.drawable.border);
TextView subject_gpa=new TextView(this);
subject_gpa.setText(""+sgpa);
subject_gpa.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,TableRow.LayoutParams.WRAP_CONTENT));
subject_gpa.setBackgroundResource(R.drawable.border);
TextView subject_grade=new TextView(this);
subject_grade.setText(""+subgrade);
subject_grade.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
subject_grade.setBackgroundResource(R.drawable.border);
}
}
You have a logical error and a runtime error here.
Why are you parsing your content of your EditText in the onCreate() method?
just remove those two lines :
//a = Integer.parseInt(String.valueOf(mark));
//b = Integer.parseInt(String.valueOf(credit));
First you don't need to parse them in the onCreate method. You parse the content in the onClick() method of your Button.
that was the logical error.
Second:
Your runtime error is being cause by the fact that you are trying to get the valueOf an EditText and not of a String. so mark should be replace by mark.getText().toString() and credit by credit.getText().toString()

Two RadioGroups with only one selected RadioButton in each of them

I have two RadioGroups in my layout. I want that only one RadioButton should be checked at a time in RadioGroup. I've tried many methods, but none of them work properly. Now I can check every RadioButton in my RadioGroups.
public class MainActivity extends ActionBarActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
String x;
char y;
int c=1;
String num,n,type;
int d,b,o,h;
String dec,bin,hex,oct;
EditText number;
EditText result;
Button convert, clear;
RadioGroup rgFrom, rgTO;
int convertedResult;
int from=R.id.r10From;
int to=R.id.r2TO;
String stNumber; //Liczba przed przeliczeniem - string
int numbResult; //Już int
String iterResult; //Liczba po przeliczeniu - string
int convResult; //Już int
//int id = ((RadioGroup).findViewById( R.id.rgFrom )).getCheckedRadioButtonId();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.etNumber);
result = (EditText) findViewById(R.id.etResult);
convert = (Button) findViewById(R.id.bCalculate);
clear = (Button) findViewById(R.id.bReset);
convert.setOnClickListener(this);
clear.setOnClickListener(this);
rgFrom = (RadioGroup) findViewById(R.id.rgFrom);
rgTO = (RadioGroup) findViewById(R.id.rgTO);
rgFrom.setOnCheckedChangeListener(this);
rgTO.setOnCheckedChangeListener(this);
}
#Override
public void onClick(View view) {
// from = (String)findViewById(R.id.rgFrom).getSelectedItem();
// int id = ((RadioGroup)findViewById( R.id.rgFrom )).getCheckedRadioButtonId();
//from = getFrom(id);
switch (view.getId()){
case R.id.r2From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r8From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r10From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r16From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r2TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.r8TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.r10TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.r16TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.bCalculate:
stNumber = number.getText().toString();
//iterResult = result.getText().toString();
//calculate();
break;
case R.id.bReset:
//reset();
break;
}
}
#Override
public void onCheckedChanged(RadioGroup rgFrom, int i) {
switch (view.getId()){
case R.id.r2From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r8From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r10From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r16From:
from = rgFrom.getCheckedRadioButtonId();
break;
case R.id.r2TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.r8TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.r10TO:
to = rgTO.getCheckedRadioButtonId();
break;
case R.id.r16TO:
to = rgTO.getCheckedRadioButtonId();
break;
}
}
}
My layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.converter_numeralsystem.app.MainActivity">
<TextView
android:layout_marginTop="20dp"
android:text="#string/number"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvNumber" />
<TextView
android:layout_marginTop="20dp"
android:layout_below="#id/tvNumber"
android:text="#string/result"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvResult" />
<EditText
android:id="#+id/etNumber"
android:layout_marginLeft="5dp"
android:hint="#string/enter_numb"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/tvNumber"
android:layout_alignBottom="#id/tvNumber"/>
<EditText
android:id="#+id/etResult"
android:layout_marginLeft="5dp"
android:hint="#string/et_result"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/tvNumber"
android:layout_alignBottom="#id/tvResult"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="#string/from"
android:id="#+id/tvFrom"
android:layout_below="#id/tvResult"
android:layout_marginTop="20dp" />
<RadioGroup
android:weightSum="100"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tvFrom"
android:id="#+id/rgFrom"
android:layout_marginTop="10dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RadioButton
android:layout_weight="50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r2From"
android:text="#string/dwa"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r8From"
android:text="#string/osiem"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="75dp" />
<RadioButton
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r10From"
android:text="#string/dziesiec"
android:layout_below="#id/r2From"
android:layout_alignStart="#id/r2From" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r16From"
android:text="#string/szesnascie"
android:layout_alignParentRight="true"
android:layout_below="#id/r8From"
android:layout_alignStart="#id/r8From"/>
</RelativeLayout>
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="#string/to"
android:id="#+id/tvTo"
android:layout_below="#id/rgFrom"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvTo"
android:layout_marginTop="10dp"
android:id="#+id/rgTO">
<RelativeLayout
android:id="#+id/rel2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RadioButton
android:checked="true"
android:layout_weight="50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r2TO"
android:text="#string/dwa"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r8TO"
android:text="#string/osiem"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="75dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r10TO"
android:text="#string/dziesiec"
android:layout_below="#id/r2TO"
android:layout_alignStart="#id/r2TO" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/r16TO"
android:text="#string/szesnascie"
android:layout_alignParentRight="true"
android:layout_below="#id/r8TO"
android:layout_alignStart="#id/r8TO"/>
</RelativeLayout>
</RadioGroup>
<LinearLayout
android:layout_marginTop="10dp"
android:weightSum="100"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/rgTO">
<Button
android:layout_weight="30"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:id="#+id/bCalculate"
android:layout_toLeftOf="#+id/bReset" />
<Button
android:layout_weight="70"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/reset"
android:id="#+id/bReset"
android:layout_alignBottom="#+id/bCalculate" />
</LinearLayout>
</RelativeLayout>
Remove the RelativeLayout from the RadiGroup. So the code would look something like:
<RadioGroup
android:id="#+id/rgFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:weightSum="100" >
<RadioButton
android:id="#+id/r2From"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="50"
android:text="dwa" />
<RadioButton
android:id="#+id/r8From"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="75dp"
android:text="osiem" />
<RadioButton
android:id="#+id/r10From"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="dziesiec" />
<RadioButton
android:id="#+id/r16From"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="szesnascie" />
</RadioGroup>
This will resolve the issue you are facing about multiple buttons being checked in same group. However, this will create a small issue in UI. I think you want 2 buttons in one line, and other two buttons in different line. As far as I know, you would have to implement your own custom layout for that. Check this post for details. Check here, too. Hope it helps a bit.

Categories