I wanted to create a simple quadratic equation solver but when I run it, it gets caught at the first if statement of each button. Any ideas?
public class MainActivity extends AppCompatActivity {
Button button1, button2;
String a_temp;
EditText b_temp;
EditText c_temp;
TextView tv1, tv2;
Double a,b,c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
a_temp = ((EditText)findViewById(R.id.editText)).getText().toString();
if (a_temp.equals("")) {
a = Double.valueOf(0);
} else {
a = Double.valueOf(a_temp);
}
b_temp = (EditText)findViewById(R.id.editText2);
if (!b_temp.getText().toString().equals("")) {
b = Double.parseDouble(b_temp.getText().toString());
}else {
b = Double.valueOf(0);
}
c_temp = (EditText)findViewById(R.id.editText3);
if (!c_temp.getText().toString().equals("")) {
c = Double.parseDouble(c_temp.getText().toString());
}else {
c = Double.valueOf(0);
}
tv1 = (TextView) findViewById(R.id.textView2);
tv2 = (TextView) findViewById(R.id.textView3);
button1 = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (a == 0) {
tv1.setText("That's not a quadratic equation");
}else {
if (b*b - 4*a*c < 0) {
tv1.setText("This quadratic equation has no real roots");
} else {
double root1 = (-b + Math.sqrt(Math.pow(b,2) - 4 * a * c))/(2*a);
double root2 = (-b - Math.sqrt(Math.pow(b,2) - 4 * a * c))/(2*a);
double result = Math.max(root1,root2);
tv1.setText(String.valueOf(result));
}
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (a == 0) {
tv2.setText("That's not a quadratic equation");
}else {
if (b * b - 4 * a * c < 0) {
tv2.setText("This quadratic equation has no real roots");
} else {
double root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
double root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
double result = Math.min(root1, root2);
tv2.setText(" " + result);
}
}
};
});
}
XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Type the operands of the quadratic equation you want to solve"
android:id="#+id/textView"
android:layout_marginTop="39dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Root #1"
android:id="#+id/button"
android:layout_marginTop="60dp"
android:layout_below="#+id/editText3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Root #2"
android:id="#+id/button2"
android:layout_marginTop="69dp"
android:layout_alignTop="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView2"
android:layout_alignBottom="#+id/button"
android:layout_alignTop="#+id/button"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:layout_toRightOf="#+id/button"
android:layout_toEndOf="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"
android:layout_alignBottom="#+id/button2"
android:layout_toRightOf="#+id/button2"
android:layout_alignTop="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|numberSigned"
android:ems="10"
android:id="#+id/editText"
android:layout_marginTop="32dp"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/textView2"
android:layout_toStartOf="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|numberSigned"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/textView2"
android:layout_toStartOf="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|numberSigned"
android:ems="10"
android:id="#+id/editText3"
android:layout_below="#+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/textView2"
android:layout_toStartOf="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="x^2"
android:id="#+id/textView4"
android:layout_alignTop="#+id/editText"
android:layout_alignLeft="#+id/textView2"
android:layout_alignStart="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="x"
android:id="#+id/textView5"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="=0"
android:id="#+id/textView6"
android:layout_alignBottom="#+id/editText3"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
</RelativeLayout>
You are comparing double values with ==.
The problem is that it will likely not be equal 0, because of the minor error it has when storing double values. For example, it will be something like 0.000000001 or -0.00000001. Instead, compare like this:
if (Math.abs(a) < 0.0000001) { ... }
Also you forgot to divide your roots by 2 * a.
So the main problem I see is, that you are assigning your values for a, b and c in the onCreate method of your activity class.
This means, as soon as your activity is created, i.e. before the user had any time to input any data into your EditText fields, you are trying to read said non-existing input - i.e. 0.
This is why in each onClick method, the first if() clause which checks for zero-values, returns true. Because the values are zero.
What you should do is move this part of each variable:
if (!c_temp.getText().toString().equals("")) {
c = Double.parseDouble(c_temp.getText().toString());
}else {
c = Double.valueOf(0);
}
into your OnClickListener classes, i.e. into the onClick methods, to "refresh" the values you are using in your calculations based on the current user input.
Related
I am trying to calculate the rectangle area in my application. I have created a simple layout but for some reason, data is not parsed into the application. I tried to print it in the console but nothing is shown.
This is my Main Class:
package com.example.week3labcode;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calcButton;
EditText number1, number2, resultFinal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calcButton = (Button)findViewById(R.id.button1);
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
resultFinal = (EditText) findViewById(R.id.edtext3);
}
#Override
public void onClick(View v){
if(v == calcButton){
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
double num1 = Double.parseDouble(number1.getText().toString());
double num2 = Double.parseDouble(number2.getText().toString());
calcRectangle(num1, num2);
}
}
public void calcRectangle(double x, double y){
double result = x * y;
System.out.println(result);
resultFinal = (EditText) findViewById(R.id.edtext3);
resultFinal.setText(Double.toString(result));
System.out.println('H' + result);
}
}
And the following code in my XML file that provides layout for the application:
<?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">
<TextView
android:id="#+id/label1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rectangle Area Calculation" />
<TextView
android:id="#+id/label2"
android:layout_below="#+id/label1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="10px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Length" />
<EditText
android:id="#+id/edtext1"
android:layout_toRightOf="#+id/label2"
android:layout_centerHorizontal="true"
android:layout_alignBaseline="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/label3"
android:layout_below="#+id/label2"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter breadth" />
<EditText
android:id="#+id/edtext2"
android:layout_toRightOf="#+id/label3"
android:layout_alignBaseline="#+id/label3"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/button1"
android:layout_below="#+id/label3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
<TextView
android:id="#+id/label4"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Area in cm2" />
<EditText
android:id="#+id/edtext3"
android:layout_toRightOf="#+id/label4"
android:layout_centerHorizontal="true"
android:layout_alignBaseline="#+id/label4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/button2"
android:layout_below="#+id/label4"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Entries" />
</RelativeLayout>
You have not set OnClickListener to your Button so calcRectangle() method is never called.
calcButton = (Button)findViewById(R.id.button1);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
double num1 = Double.parseDouble(number1.getText().toString());
double num2 = Double.parseDouble(number2.getText().toString());
calcRectangle(num1, num2);
}
});
OR
calcButton.setOnClickListener(this);
**activity_main xml**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context="com.example.hynes.equations.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please select what type of equation to solve"
android:id="#+id/textView2" />
<Button
android:text="Check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/textView3"
android:layout_alignEnd="#+id/textView3"
android:layout_marginRight="230dp"
android:layout_marginEnd="230dp"
android:id="#+id/button2" />
<TextView
android:layout_centerVertical="true"
android:id="#+id/textView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_height="50dp"
android:layout_width="250dp"
android:layout_alignRight="#+id/textView2"
android:layout_alignEnd="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_above="#+id/button2"
android:layout_alignRight="#+id/textView5"
android:layout_alignEnd="#+id/textView5"
android:layout_marginRight="170dp"
android:layout_marginEnd="170dp"
android:layout_marginBottom="36dp"
android:id="#+id/editText2" />
<RadioGroup android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RadioButton
android:text="Addition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp"
android:id="#+id/addition"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:text="Subtraction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/subtraction"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:text="Division"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="16dp"
android:id="#+id/division"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:text="Multiplication"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:id="#+id/multiplication"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
`
MAIN ACTIVITY
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;`
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private int x;
private int y;
public int a;
public int b;
Random random = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view){
TextView display = (TextView) findViewById(R.id.textView5);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
int btnID = radioGroup.getCheckedRadioButtonId();
switch(btnID){
case R.id.addition:
x = random.nextInt(100);
y = random.nextInt(100);
display.setText(x + "+" + y + "=");
break;
case R.id.subtraction:
x = random.nextInt(100);
y = random.nextInt(100);
display.setText(x + "-" + y + "=");
break;
case R.id.division:
y = random.nextInt(5);
x = y*2;
display.setText(x + "/" + y + "=");
break;
case R.id.multiplication:
x = random.nextInt(10);
y = random.nextInt(10);
display.setText(x + "*" + y + "=");
break;
}
public void onClickCheck(View view){
TextView result = (TextView) findViewById(R.id.textView5);
EditText ans = (EditText) findViewById(R.id.editText2);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
int btnID = radioGroup.getCheckedRadioButtonId();
if(boolean(RadioButton) findViewById(R.id.addition)) ){
int key = x+y;
int try = 0;
while(!ans.equals(key)){
try = try + 1;
if(try ==0){
result.setText("Incorrect, try again!");
try++
}else if (try>2){
result.setText("Incorrect, the answer is : " + key);
}
if(ans.equals(key)){
result.setText("You are correct !");
}
}
}
}
}
}
}
This is a android studio app that's suppose to randomly generate a math equation upon creation which I've done. There's addition, subtraction, division, and multiplication. My random equation generator works perfectly. But I'm stuck at my onClickCheck method which i want to get the user's answer/input and check to see if it's correct or incorrect and display a message accordingly. My onClick method is wrong but it's a start. I don't know what methods i need to get my code to accept inputs properly. Any help would be appreciated.
It looks like you aren't assigning an OnClickListener to the button.
You need to put:(in onCreate)
Button button = (Button)findViewById(R.id.button2);
button.setOnClickListener(onClickCheck);
or
Button button = (Button)findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickCheck(view);
}
});
Same for the radio button.
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());
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");
}
}
});
I'm currently developing an mobile grocery app. I just want to ask you why my code in layout Y cant throw the details from different activity, but layout X can! As you can see, I used checkbox to checked all items you want to purchase, but in Layout Y, if u checked the item you want and click the "add to cart" button it crashed.
Tho I reedit the code based on respective information and copy to layout Y.
Here is my Code
Baby Diaper (Layout X) Java
public class Baby_Diaper extends ActionBarActivity {
ArrayList<String> selection = new ArrayList<String>();
TextView final_text;
Button addtoCart;
Intent i = new Intent(this, Shopping_List.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baby__diaper);
addtoCart = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_diaper);
}
public void SelectItem (View view) {
boolean checked = ((CheckBox) view) .isChecked();
switch (view.getId())
{
case R.id.pampers:
if(checked)
{selection.add("Pampers");}
else
{
selection.remove ("Pampers");
}
break;
case R.id.huggies:
if(checked)
{selection.add("Huggies");}
else
{
selection.remove ("Huggies");
}
break;
case R.id.johnsons:
if(checked)
{selection.add("Johnsons");}
else
{
selection.remove ("Johnsons");
}
break;
case R.id.supreme:
if(checked)
{selection.add("Supreme");}
else
{
selection.remove ("Supreme");
}
break;
}
}
public void ocaddtocart(View view){
String final_shopping_selection = "";
for (String Selections : selection){
final_shopping_selection = final_shopping_selection + Selections + "\n";
}
final_text.setText(final_shopping_selection);
final_text.setEnabled(true);}
public void ocgtshoppinglist (View view){
Intent x = new Intent(Baby_Diaper.this, Shopping_List.class);
x.putExtra("items", final_text.getText().toString());
startActivity(x);
}
Baby Food (Layout Y) Java
public class Baby_Food extends ActionBarActivity {
ArrayList<String> selection = new ArrayList<String>();
TextView final_text;
Button addtoFood;
Intent i = new Intent(this, Shopping_List.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addtoFood = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_food);
setContentView(R.layout.activity_baby__food);
}
public void SelectItem (View view) {
boolean checked = ((CheckBox) view) .isChecked();
switch (view.getId())
{
case R.id.coryandgate:
if(checked)
{selection.add("Cory & Gate");}
else
{
selection.remove ("Cory & Gate");
}
break;
case R.id.gerber:
if(checked)
{selection.add("Gerber");}
else
{
selection.remove ("Gerber");
}
break;
case R.id.hipp:
if(checked)
{selection.add("Hipp");}
else
{
selection.remove ("Hipp");
}
break;
}
}
public void ocaddtocart(View view){
String final_shopping_selection = "";
for (String Selections : selection){
final_shopping_selection = final_shopping_selection + Selections + "\n";
}
final_text.setText(final_shopping_selection);
final_text.setEnabled(true);
}
public void ocgtshoppinglist (View view){
Intent x = new Intent(Baby_Food.this, Shopping_List.class);
x.putExtra("items", final_text.getText().toString());
startActivity(x);
}
Baby Diaper (Layout X) XML
<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"
tools:context="com.example.admin.mobile_grocery.Baby_Diaper"
android:id="#+id/baby_diaper">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pampers"
android:id="#+id/pampers"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:checked="false"
android:onClick="SelectItem"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/huggies"
android:id="#+id/huggies"
android:layout_below="#+id/pampers"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
android:onClick="SelectItem"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/johnsons"
android:id="#+id/johnsons"
android:layout_below="#+id/huggies"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
android:onClick="SelectItem"
android:inputType="textNoSuggestions"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/supreme"
android:id="#+id/supreme"
android:layout_below="#+id/johnsons"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
android:onClick="SelectItem"
android:inputType="textNoSuggestions"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/addtocart"
android:id="#+id/addtocart"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:inputType="textNoSuggestions"
android:onClick="ocaddtocart" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hello Shoppers!"
android:id="#+id/final_shopping_diaper"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO TO SHOPPING LIST"
android:id="#+id/gt_shopping_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="ocgtshoppinglist"
/>
Baby Food (Layout Y) XML
<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"
tools:context="com.example.admin.mobile_grocery.Baby_Food"
android:id="#+id/baby_food">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cory & Gate"
android:id="#+id/coryandgate"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:checked="false"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gerber"
android:id="#+id/gerber"
android:layout_below="#+id/coryandgate"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hipp"
android:id="#+id/hipp"
android:layout_below="#+id/gerber"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD TO CART / REMOVE"
android:id="#+id/addtocart"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="ocaddtocart"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hello Shoppers!"
android:id="#+id/final_shopping_food"
android:layout_below="#+id/hipp"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO TO SHOPPING LIST"
android:id="#+id/gt_shopping_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="ocgtshoppinglist" />
When I clicked the link on Logcat it pointed me to
final_text.setText(final_shopping_selection); of layout Y
try to change it in Y
addtoFood = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_food);
setContentView(R.layout.activity_baby__food);
to
setContentView(R.layout.activity_baby__food);
addtoFood = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_food);
I think your text view is null in addtocart method.