My TextView in Android doesn't update - java

Although I've checked the solutions for the related questions in this website, I couldn't solve my problem. I'm trying to build a quiz app that takes the correct answer, adds 1 to the score and updates the score on the score TextView. I tried calling the score method through android:onClick and also tried the setOnClickListener methods but none of them seem to work.
This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Canada Quiz"
android:textSize="16sp"
android:textColor="#000000"
android:textStyle="bold"
android:layout_marginBottom="16dp"
android:layout_gravity="center"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name"
android:layout_marginBottom="8dp"
/>
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginBottom="16dp"
android:textColor="#000000"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1. What is the capital of Canada?"
android:textSize="20dp"
android:textColor="#000000"
android:textStyle="bold"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/tokyo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tokyo"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/newYork"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New York"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/ottawa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ottawa"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/hongKong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hong Kong"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:onClick="calculateScore"
android:textSize="16dp"/>
</RadioGroup>
<Button
android:id="#+id/scoreButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate score"
android:layout_marginTop="16dp"
/>
</LinearLayout>
</ScrollView>
And this is my Java:
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioButton rb = (RadioButton)findViewById(R.id.ottawa);
Button calculate = (Button) findViewById(R.id.scoreButton);
final TextView scoreShow = (TextView) findViewById(R.id.scoreText);
final boolean rbChecked = rb.isChecked();
calculate.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
if(rbChecked){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
}
});
}
// public void calculateScore(){
// RadioButton rb = (RadioButton)findViewById(R.id.ottawa);
// //Button calculate = (Button) findViewById(R.id.scoreButton);
// TextView scoreShow = (TextView) findViewById(R.id.scoreText);
//
// boolean rbChecked = rb.isChecked();
// if(rbChecked){
// score += 1;
// scoreShow.setText("Your score is: " + score + "/10");
// }
// }
}
Honestly, it really looks like it would work but it doesn't.

You are only storing the value of the checked state when the view is loaded and it never is updated.
Always check rb.isChecked() inside the click listener instead of storing the boolean value outside of it.

It should be:
if(rbChecked.isChecked()){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}

you need to check for the state of radiobutton when user click on calculate button....your code should be like this...
calculate.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
rbChecked = rb.isChecked();
if(rbChecked){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
}
});

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

Showing text from string through TextView after pressing RadioButton

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.

Android Studio Counter TextView Field not updating

Assuming Imports and Stuff
Im trying to build a simple Calorie Counter, but having a trouble displaying
the number of calories. I also want it to add to the previous input..
for instance if the user enters 500, 400, 300 the total in the TextField
should be 1200.
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:id="#+id/CalorieAdd"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="rav_singh.caloriecounter.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="Current Calories "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/caloriesNeeded"
android:textSize="30dp"
android:layout_marginTop="41dp"
android:layout_marginEnd="69dp"
android:layout_below="#+id/calCount"
android:layout_alignParentEnd="true" />
<TextView
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calCount"
android:textAlignment="center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="40dp" />
<Button
android:text="Add "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calorieAdd"
android:layout_marginTop="88dp"
android:layout_below="#+id/caloriesNeeded"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/calorieinput"
android:hint="Add Calories "
android:layout_marginTop="12dp"
android:layout_below="#+id/caloriesNeeded"
android:layout_alignStart="#+id/caloriesNeeded"
android:textAlignment="center" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
EditText input;
TextView calTotal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calTotal = (TextView) findViewById(R.id.calCount);
input = (EditText) findViewById(R.id.calorieinput);
Button calorieAdd = (Button) findViewById(R.id.calorieAdd);
calTotal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Float n1 = Float.valueOf(input.getText().toString());
calTotal.setText(Float.toString(n1));
}
});
}
}
previous input.. for instance if the user enters 500, 400, 300 the
total in the TextField should be 1200
Add both TextView and EditText data before updating counter in TextView like:
#Override
public void onClick(View view) {
float n0 = Float.parseFloat(calTotal.getText().toString());
float n1 = Float.parseFloat(input.getText().toString());
calTotal.setText(Float.toString(n0+n1));
}
Also added empty check for EditText before parsing value to Float to avoid NumberFormatException Exception.
try
if(input.getText().toString().trim().length() > 0)
float n1 = Float.parseFloat(input.getText().toString());
instead of:
Float n1 = Float.valueOf(input.getText().toString());

Wrong textview is being updated

In the onCreate() method I am updating 2 TextViews to be blank. For some reason it is setting two other TextViews to be blank. I have followed my logic and can not see what is going wrong.
here is my onCreate() method.
import android.widget.TextView;
public class MainActivity extends Activity {
private int purpleDrinks; //number of purple drinks
private int greenDrinks; //number of green drinks
private int redDrinks; //number of red drinks
private int blueDrinks; //number of blue drinks
private TextView purpleCount; //number of purple drinks display
private TextView greenCount; //number of green drinks display
private TextView redCount; //number of red drinks display
private TextView blueCount; //number of blue drinks display
private TextView purchaseConfirm; //displays what the user bought
private TextView outOfStock; //lets the user know when the item is out of stock.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ( savedInstanceState == null ) // the app just started running
{
purpleDrinks = 10;
greenDrinks = 10;
redDrinks = 10;
blueDrinks = 10;
} // end if
purpleCount = (TextView) findViewById(R.id.purpleCount);
greenCount = (TextView) findViewById(R.id.greenCount);
redCount = (TextView) findViewById(R.id.redCount);
blueCount = (TextView) findViewById(R.id.blueCount);
purchaseConfirm = (TextView) findViewById(R.id.purchaseConfirm);
outOfStock = (TextView) findViewById(R.id.outOfStock);
purchaseConfirm.setText("");
outOfStock.setText("");
purpleCount.setText(purpleDrinks + "");
greenCount.setText(greenDrinks + "");
redCount.setText(redDrinks + "");
blueCount.setText(blueDrinks + "");
}
here is the xml code: the ids are correct.
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background= "#D5E3EA"
tools:context=".MainActivity" >
<ImageButton
android:id="#+id/greenCann"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="25dp"
android:layout_marginTop="26dp"
android:src="#drawable/greencan" />
<ImageButton
android:id="#+id/redCann"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/greenCann"
android:layout_marginRight="25dp"
android:src="#drawable/redcan" />
<ImageButton
android:id="#+id/purpleCann"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/redCann"
android:layout_marginRight="25dp"
android:src="#drawable/purplecan" />
<ImageButton
android:id="#+id/blueCann"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/purpleCann"
android:layout_marginRight="25dp"
android:src="#drawable/bluecan" />
<Button
android:id="#+id/restockButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="54dp"
android:text="#string/restock" />
<TextView
android:id="#+id/purpleCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/purpleCann"
android:layout_marginBottom="18dp"
android:layout_toLeftOf="#+id/purpleCann"
android:text="TextView" />
<TextView
android:id="#+id/redCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/redCann"
android:layout_marginBottom="20dp"
android:layout_toLeftOf="#+id/redCann"
android:text="TextView" />
<TextView
android:id="#+id/greenCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/greenCann"
android:layout_marginBottom="20dp"
android:layout_toLeftOf="#+id/greenCann"
android:text="TextView" />
<TextView
android:id="#+id/blueCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/blueCann"
android:layout_marginBottom="20dp"
android:layout_toLeftOf="#+id/blueCann"
android:text="TextView" />
<TextView
android:id="#+id/outOfStock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/restockButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="14dp"
android:text="TextView" />
<TextView
android:id="#+id/purchaseConfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/outOfStock"
android:layout_alignBottom="#+id/outOfStock"
android:layout_alignLeft="#+id/outOfStock"
android:text="TextView" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/greenCount"
android:layout_toLeftOf="#+id/restockButton"
android:text="#string/greenSoda2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/redCount"
android:layout_alignBottom="#+id/redCount"
android:layout_alignLeft="#+id/textView5"
android:text="#string/redSoda"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/purpleCount"
android:layout_alignBottom="#+id/purpleCount"
android:layout_alignLeft="#+id/textView6"
android:text="#string/purpleSoda"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/blueCount"
android:layout_alignBottom="#+id/blueCount"
android:layout_alignLeft="#+id/textView7"
android:text="#string/blueSoda"
android:textAppearance="?android:attr/textAppearanceMedium" />
here is a screenshot of the app:
does anybody know what is going on?

Categories