Hello fellow programmers!
I have a very disturbing situation here...I'm developing an Android App with several activities.In them I have buttons.The app itself is for measuring calories and other sports releated stuff.
I have a calorie calculator which I have built in the app,spread across 2 activities.In activity 1,the calculator measures the Basal Metabolic Rate and In the second activity,the app calculates the calories needed,when clicking a button for the desired activity level.My app crashes in the second activity,when clicking "Sedentary" button and I have no clue why,because these buttons are built just like the buttons in my first activity.I'll post photos and my code so you can get orientation.
Btw,the app crashes also when clicking "Null Data" in the first activity with the BMR...The button doesn't have any coding on it and does nothing.I'm not calling calculate() method in the second activity,instead I tried doing the button click in the main method,but it still didn't work.
Hello fellow programmers!
I have a very disturbing situation here...I'm developing an Android App with several activities.In them I have buttons.The app itself is for measuring calories and other sports releated stuff.
I have a calorie calculator which I have built in the app,spread across 2 activities.In activity 1,the calculator measures the Basal Metabolic Rate and In the second activity,the app calculates the calories needed,when clicking a button for the desired activity level.My app crashes in the second activity,when clicking "Sedentary" button and I have no clue why,because these buttons are built just like the buttons in my first activity.I'll post photos and my code so you can get orientation.
Btw,the app crashes also when clicking "Null Data" in the first activity with the BMR...The button doesn't have any coding on it and does nothing.I'm not calling calculate() method in the second activity,instead I tried doing the button click in the main method,but it still didn't work.First ActivitySecond Activity
`package com.petartonkov.foodandsportsinfo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class CalorieCalculator extends AppCompatActivity {
public Button nextstepbtn;
public TextView BMR;
public EditText height;
public EditText weight;
public EditText age;
public void calculate() {
final Button calculateBMR = (Button) findViewById(R.id.CalcBtn);
final TextView BMR = (TextView) findViewById(R.id.textView_BMR);
final EditText weight = (EditText) findViewById(R.id.editText_weight);
final EditText height = (EditText) findViewById(R.id.editText_height);
final EditText age = (EditText) findViewById(R.id.editText_age);
assert calculateBMR != null;
calculateBMR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
assert weight != null;
float weight1 = Float.parseFloat(weight.getText().toString());
assert height != null;
float height1 = Float.parseFloat(height.getText().toString());
assert age != null;
float age1 = Float.parseFloat(age.getText().toString());
float BMR1 = (13.75f * weight1 + 5.003f * height1 - 6.755f * age1) + 66.75f;
assert BMR != null;
BMR.setText(Float.toString(BMR1));
}
});
}
public void calculate1() {
final Button calculateBMR = (Button) findViewById(R.id.CalcBtnFemale);
final TextView BMR = (TextView) findViewById(R.id.textView_BMR);
final EditText weight = (EditText) findViewById(R.id.editText_weight);
final EditText height = (EditText) findViewById(R.id.editText_height);
final EditText age = (EditText) findViewById(R.id.editText_age);
assert calculateBMR != null;
calculateBMR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
assert weight != null;
float weight1 = Float.parseFloat(weight.getText().toString());
assert height != null;
float height1 = Float.parseFloat(height.getText().toString());
assert age != null;
float age1 = Float.parseFloat(age.getText().toString());
float BMR1 = (9.563f * weight1 + 1.85f * height1 - 4.676f * age1) + 655.1f;
assert BMR != null;
BMR.setText(Float.toString(BMR1));
}
});
}
public void init4(){
nextstepbtn = (Button)findViewById(R.id.NextStepBtn);
nextstepbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(getBaseContext(), CalorieCalculatorSecondActivity.class);
intent1.putExtra("BMR", (Parcelable) BMR);
startActivity(intent1);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_calculator);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
init4();
calculate();
calculate1();
}
}
`
` package com.petartonkov.foodandsportsinfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CalorieCalculatorSecondActivity extends CalorieCalculator {
public void totalcalories() {
final Button calculateBtn = (Button) findViewById(R.id.button_sedentary);
final TextView totalcalories = (TextView) findViewById(R.id.textView_totalcalories);
final TextView BMR = (TextView) findViewById(R.id.textView_BMR);
assert calculateBtn != null;
calculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
assert BMR != null;
float BMR2 = Float.parseFloat(BMR.getText().toString());
float totalcalories1 = BMR2 * 1.2f;
assert totalcalories != null;
totalcalories.setText(Float.toString(totalcalories1));
}
});
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_calculator_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle extras = getIntent().getExtras();
final Button calcBtn = (Button)findViewById(R.id.button_sedentary);
final TextView totalcalories2 = (TextView)findViewById(R.id.textView_totalcalories);
final TextView BMR1 = (TextView) findViewById(R.id.textView_BMR);
assert calcBtn != null;
calcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
assert BMR1 != null;
float BMR3 = Float.parseFloat(BMR1.getText().toString());
float totalcalories4 = BMR3 * 1.2f;
assert totalcalories2 != null;
totalcalories2.setText(Float.toString(totalcalories4));
}
});
}
}
`
`
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter your data below to calculate your BMR(Basal Metabolic Rate) and then enter your level of physical activity to determine your daily calorie needs.BMR-this number is the calories needed from the body to maintain basic living functions."
android:id="#+id/textView2"
android:textColor="#040404"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="go to next step"
android:id="#+id/NextStepBtn"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="BMR:"
android:id="#+id/textView11"
android:textColor="#070707"
android:layout_below="#+id/CalcBtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="CAL"
android:id="#+id/textView13"
android:layout_alignTop="#+id/textView_BMR"
android:layout_centerHorizontal="true"
android:textColor="#980606" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NULL DATA"
android:id="#+id/btn_nulldata"
android:layout_alignBaseline="#+id/NextStepBtn"
android:layout_alignBottom="#+id/NextStepBtn"
android:layout_alignRight="#+id/textView2"
android:layout_alignEnd="#+id/textView2"
android:onClick="onCheckboxClicked"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText_age"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="27dp"
android:hint="Enter age"
android:layout_below="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText_weight"
android:layout_below="#+id/editText_age"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Enter weight(In KG)"
android:layout_alignRight="#+id/NextStepBtn"
android:layout_alignEnd="#+id/NextStepBtn" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText_height"
android:layout_below="#+id/editText_weight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Enter height(In CM)" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView_BMR"
android:layout_alignTop="#+id/textView11"
android:layout_toLeftOf="#+id/NextStepBtn"
android:layout_toStartOf="#+id/NextStepBtn"
android:textColor="#980606" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CALCULATE BMR-MALE"
android:id="#+id/CalcBtn"
android:background="?attr/colorPrimary"
android:textColor="#ffffff"
android:layout_marginTop="31dp"
android:layout_below="#+id/editText_height"
android:layout_toLeftOf="#+id/textView13"
android:layout_toStartOf="#+id/textView13" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CALCULATE BMR-FEMALE"
android:id="#+id/CalcBtnFemale"
android:background="?attr/colorPrimary"
android:textColor="#ffffff"
android:layout_alignBottom="#+id/CalcBtn"
android:layout_toRightOf="#+id/textView13"
android:layout_toEndOf="#+id/textView13" />
</RelativeLayout>`
`
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="SELECT YOUR LEVEL OF PHYSICAL ACTIVITY:"
android:id="#+id/textView10"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sedentary"
android:id="#+id/button_sedentary"
android:layout_below="#+id/textView10"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="true"
android:enabled="true"
android:onClick="setContentView" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="moderately active"
android:id="#+id/button_moderatelyactive"
android:layout_alignTop="#+id/button_sedentary"
android:layout_alignRight="#+id/textView14"
android:layout_alignEnd="#+id/textView14" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Very active"
android:id="#+id/button_veryactive"
android:layout_below="#+id/button_sedentary"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Extremely active"
android:id="#+id/button_extremelyactive"
android:layout_alignBottom="#+id/button_veryactive"
android:layout_alignLeft="#+id/button_moderatelyactive"
android:layout_alignStart="#+id/button_moderatelyactive" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Sedentary - Little or no exercise,little walking"
android:id="#+id/textView14"
android:layout_below="#+id/button_veryactive"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#e10e0e" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Lighty active - light exercise 1-3 times/week + walking"
android:id="#+id/textView15"
android:layout_below="#+id/textView14"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#e10e0e" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Moderately active - exercise 3-5 times/week + walking"
android:id="#+id/textView16"
android:layout_below="#+id/textView15"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#e10e0e" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Very active - hard exercise 5-7 times/week + walking"
android:id="#+id/textView17"
android:textColor="#e10e0e"
android:layout_below="#+id/textView16"
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:text="TOTAL CALORIES NEEDED:"
android:id="#+id/textView18"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#080808" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView_totalcalories"
android:layout_alignTop="#+id/textView18"
android:layout_toRightOf="#+id/textView18"
android:layout_toEndOf="#+id/textView18"
android:editable="false"
android:enabled="false"
android:text="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="CAL"
android:id="#+id/textView20"
android:layout_alignBottom="#+id/textView_totalcalories"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#090909" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NULL DATA"
android:id="#+id/btn_nulldata2"
android:layout_marginBottom="48dp"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/button_sedentary"
android:layout_alignEnd="#+id/button_sedentary" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Extra active - hard exercise 5-7 times/week + physical job + walking"
android:id="#+id/textView3"
android:textColor="#e10e0e"
android:layout_below="#+id/textView17"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lightly active"
android:id="#+id/button"
android:layout_alignBottom="#+id/button_extremelyactive"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/button_extremelyactive"
android:layout_toEndOf="#+id/button_extremelyactive" />
</RelativeLayout>`
`
--------- beginning of crash
06-14 06:10:35.167 2481-2481/com.petartonkov.foodandsportsinfo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.petartonkov.foodandsportsinfo, PID: 2481
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at com.petartonkov.foodandsportsinfo.CalorieCalculatorSecondActivity$2.onClick(CalorieCalculatorSecondActivity.java:44)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
`
This metod is throwing
calcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
assert BMR1 != null;
float BMR3 = Float.parseFloat(BMR1.getText().toString());
float totalcalories4 = BMR3 * 1.2f;
assert totalcalories2 != null;
totalcalories2.setText(Float.toString(totalcalories4));
}
});
You have no TextView (BMR1) with the id of textView_BMR in your secondActivity layout
To pass the value from one activity to another you can use Intent extra
Intent extra is a bundle of additional information you want to pass from one activity to another. You can create extras like this
//First Activity
Intent i = new Intent(FirstActiviy.this, SecondActivity.class);
String value = "some string you want to put in the extra";
int value2 = 14
//put extra as key-value pairs
i.putExtra("KEY", value);
i.putExtra("KEY2", value2);
startActivity(i);
//Second activity
//Get the values from previous Activity by keys you set
String stringValueFromPreviousActivity = getIntent().getStringExtra("key");
//Note: when you getting integer as the second parameter pass the default value if there is no passed integer
int intValueFromPreviousActiviy = getIntent().getIntExtra("key",4);
I tried setting up the calculator in one activity...I rearanged the buttons and guess what..?My float from BMR TextView is NULL,althrough I have a string in BMR TextView.Why is this happening?I wrote the code for the total calories in another method,in the first activity.
public void calculatetotalcalories()
{
final Button calcbtn_sedentary = (Button)findViewById(R.id.button_sedentary);
final TextView totalcalories = (TextView)findViewById(R.id.textView_totalcalories);
calcbtn_sedentary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float BMRconverted= Float.parseFloat(String.valueOf(BMR));
float totalcalories1 =BMRconverted*1.2f;
totalcalories.setText(Float.toString(totalcalories1));
}
});
I solved the problem.It was an null object reference in the start of the activity.Everything now works!
Related
I am building a BMR calculator with radio buttons for Male and Female.
I am using a switch case to calculate BMR for each but it doesn't seem to work.
Nothing happens when I press the calculate button.
It seems to work okay when I calculate it directly i.e without switch case, the ResultTextView becomes visible and shows the answers. I apologize if I am repeating the question, I am new to programming. Please ignore the formulae for BMR I know they aren't correct I just put them for testing.
Following is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class BmrActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton bmrFemaleRadioButton;
RadioButton bmrMaleRadioButton;
EditText bmrAgeEditText;
EditText bmrWeightEditText;
EditText bmrHeightEditText;
Button bmrCalculateButton;
TextView bmrResultTextView;
Double age;
Double weight;
Double height;
Double resultBmr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmr);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
bmrFemaleRadioButton = findViewById(R.id.bmrFemaleRadioButton);
bmrMaleRadioButton = findViewById(R.id.bmrMaleRadioButton);
bmrAgeEditText = findViewById(R.id.bmrAgeEditText);
bmrWeightEditText = findViewById(R.id.bmrWeightEditText);
bmrHeightEditText = findViewById(R.id.bmrHeightEditText);
bmrCalculateButton = findViewById(R.id.bmrCalculateButton);
bmrResultTextView = findViewById(R.id.bmrResultTextView);
bmrFemaleRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmrAgeEditText.setVisibility(View.VISIBLE);
bmrWeightEditText.setVisibility(View.VISIBLE);
bmrHeightEditText.setVisibility(View.VISIBLE);
bmrCalculateButton.setVisibility(View.VISIBLE);
}
});
bmrMaleRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmrAgeEditText.setVisibility(View.VISIBLE);
bmrWeightEditText.setVisibility(View.VISIBLE);
bmrHeightEditText.setVisibility(View.VISIBLE);
bmrCalculateButton.setVisibility(View.VISIBLE);
}
});
}
public void calculateBmr(final View view){
age = Double.parseDouble(bmrAgeEditText.getText().toString());
weight = Double.parseDouble(bmrWeightEditText.getText().toString());
height = Double.parseDouble(bmrHeightEditText.getText().toString());
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.bmrFemaleRadioButton:
resultBmr = age + weight + height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
case R.id.bmrMaleRadioButton:
resultBmr = age * weight * height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
}
}
});
}
}
Following is my XML layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".BmrActivity">
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/bmrFemaleRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Female" />
<RadioButton
android:id="#+id/bmrMaleRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Male" />
</RadioGroup>
<EditText
android:id="#+id/bmrAgeEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Enter your age"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/radioGroup" />
<EditText
android:id="#+id/bmrWeightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Enter your weight in kgs"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrAgeEditText" />
<EditText
android:id="#+id/bmrHeightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Enter your height in cms"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrWeightEditText" />
<Button
android:id="#+id/bmrCalculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:onClick="calculateBmr"
android:text="Calculate"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrHeightEditText" />
<TextView
android:id="#+id/bmrResultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="monospace"
android:text="Answer"
android:textAlignment="center"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrCalculateButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
You are doing it wrong. You are calling setOnCheckedChangeListener() when the button has been clicked, but by that time the radio button has already been checked. The onCheckedChange() is called when the change occurs.
Instead of setting a listener, you can directly get the checked item id by calling radioGroup.getCheckedRadioButtonId()
like this
switch(radioGroup.getCheckedRadioButtonId()){
case R.id.bmrFemaleRadioButton:
resultBmr = age + weight + height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
case R.id.bmrMaleRadioButton:
resultBmr = age * weight * height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
}
Did you try move get age, weight, height inside onCheckChanged. Because it only parse one time and not update again.
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);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Basically, I'm trying to make this eating healthy app based on their BMI. The calculator is done but now I'm stuck at this where the user clicks on one of these 3 buttons and that list in the Spinner item and the ImageView changes accordingly (if user clicks breakfast button, then the spinner list and image change to breakfast and so). Even the image is not working. The app runs but when I click the button it terminates and I don't know how to fix it. if it's possible, can you guys also let me know the way I'm doing my Spinner will work or not?
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button Toch;
Button BTbtn;
Button LunchBtn;
Button DinnerBtn;
Button Submit;
EditText inweight;
EditText inheight;
EditText inage;
TextView BMR;
RadioButton rdM;
RadioButton rdF;
ImageView maimage;
Spinner spinner;
/**
Button Submit = (Butt
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button Submit = (Button)findViewById(R.id.Sumbit);
final Button Toch = (Button) findViewById(R.id.Toch);
Toch.setOnClickListener(this);
final Button BTbtn = (Button) findViewById(R.id.BTbtn);
BTbtn.setOnClickListener(this);
final Button LunchBtn = (Button) findViewById(R.id.LunchBtn);
LunchBtn.setOnClickListener(this);
final Button DinnerBtn = (Button) findViewById(R.id.DinnerBtn);
DinnerBtn.setOnClickListener(this);
//EditText
final EditText inweight = (EditText) findViewById(R.id.inweight);
final EditText inheight = (EditText) findViewById(R.id.inheight);
final EditText inage = (EditText) findViewById(R.id.inage);
//Text View
final TextView BMR = (TextView) findViewById(R.id.BMR);
// final TextView FDName=(TextView)findViewById(R.id.FDName);
//RadioButton
final RadioButton rdM = (RadioButton) findViewById(R.id.rdM);
final RadioButton rdF = (RadioButton) findViewById(R.id.rdF);
//ImageView
final ImageView maimage = (ImageView) findViewById(R.id.maimage);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.BTbtn: {
maimage.setImageResource(R.drawable.breakfast);
//ArrayAdapter bList = ArrayAdapter.createFromResource(getApplicationContext(), android.R.array.breakfastList, android.R.layout.simple_dropdown_item_1line);
}
case R.id.LunchBtn: {
maimage.setImageResource(R.drawable.dinner);
//ArrayAdapter lList = ArrayAdapter.createFromResource(getApplicationContext(), android.R.array.lunchList, android.R.layout.simple_dropdown_item_1line);
}
case R.id.DinnerBtn: {
maimage.setImageResource(R.drawable.lunch);
//ArrayAdapter dList = ArrayAdapter.createFromResource(getApplicationContext(), android.R.array.dinnerList, android.R.layout.simple_dropdown_item_1line);
}
case R.id.Sumbit: {
double weight = Double.parseDouble(inweight.getText().toString());
double height = Double.parseDouble(inheight.getText().toString());
double age = Double.parseDouble(inage.getText().toString());
double gender;
if (rdM.isChecked()) {
gender = 66;
double ans = gender + (13.7 * weight) + (5 * height) - (6.8 * age);
BMR.setText("" + (int) ans);
}
if (rdF.isChecked()) {
gender = 655;
double ans = gender + (9.6 * weight) + (1.8 * height) - (4.7 * age);
BMR.setText("Your Calories require : " + (int) ans);
}
}
case R.id.Toch: {
inweight.setHint(R.string.chweight);
inheight.setHint(R.string.chhight);
inage.setHint(R.string.chage);
}
}
}
}
R.layout.activity_main:
<?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: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.cmleu_000.myapplication.MainActivity">
<TextView
android:text="Food Name:"
android:textSize="18dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<Button
android:id="#+id/BTbtn"
android:text="Breakfast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/LunchBtn"
android:layout_alignRight="#+id/radioGroup2"
android:layout_alignEnd="#+id/radioGroup2" />
<Button
android:id="#+id/LunchBtn"
android:text="Lunch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/DinnerBtn"
android:layout_alignRight="#+id/BTbtn"
android:layout_alignEnd="#+id/BTbtn" />
<Button
android:id="#+id/DinnerBtn"
android:text="Dinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/maimage"
android:layout_alignLeft="#+id/LunchBtn"
android:layout_alignStart="#+id/LunchBtn" />
<ImageView
android:id="#+id/maimage"
android:src="#drawable/dinner"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_above="#+id/qweight"
android:layout_alignLeft="#+id/qhight"
android:layout_alignStart="#+id/qhight" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Sumbit"
android:layout_alignRight="#+id/Sumbit"
android:layout_alignEnd="#+id/Sumbit"
android:id="#+id/radioGroup2">
<RadioButton
android:id="#+id/rdF"
android:text="F"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/rdM"
android:layout_toRightOf="#+id/rdM"
android:layout_toEndOf="#+id/rdM"
android:layout_gravity="left" />
<RadioButton
android:id="#+id/rdM"
android:text="M"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioGroup"
android:layout_toRightOf="#+id/qage"
android:layout_toEndOf="#+id/qage"
android:layout_gravity="left" />
</RadioGroup>
<TextView
android:text="Your weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/qweight"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/inweight"
android:hint="Plase input your weight (KG)"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/qhight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="Your height"
android:id="#+id/qhight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/inheight"
android:layout_alignRight="#+id/qweight"
android:layout_alignEnd="#+id/qweight" />
<EditText
android:id="#+id/inheight"
android:hint="Please input your height (CM)"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/qage"
android:layout_alignRight="#+id/inweight"
android:layout_alignEnd="#+id/inweight" />
<TextView
android:text="Your age"
android:id="#+id/qage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/inage"
android:layout_alignLeft="#+id/BMR"
android:layout_alignStart="#+id/BMR" />
<EditText
android:id="#+id/inage"
android:hint="Please input your age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Sumbit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/Sumbit"
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:text="Your BMR"
android:id="#+id/BMR"
android:textStyle="bold"
android:textSize="10pt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/inheight"
android:layout_alignStart="#+id/inheight" />
<Button
android:text="中文"
android:id="#+id/Toch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/BMR"
android:layout_toLeftOf="#+id/Sumbit"
android:layout_toStartOf="#+id/Sumbit" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_above="#+id/BTbtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Logcat:
08-24 22:43:52.039 3104-3104/com.example.cmleu_000.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cmleu_000.myapplication, PID: 3104
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.example.cmleu_000.myapplication.MainActivity.onClick(MainActivity.java:92)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-24 22:43:53.601 3104-3110/com.example.cmleu_000.myapplication W/art: Suspending all threads took: 8.662ms
08-24 22:44:10.123 3104-3110/com.example.cmleu_000.myapplication W/art: Suspending all threads took: 5.787ms
*new error after edditing
You've defined the maimage variable twice. The class variable maimage that you're trying to access in the onClick(...) method is null (it was never initialized).
To fix this, change:
final ImageView maimage = (ImageView) findViewById(R.id.maimage);
to:
maimage = (ImageView) findViewById(R.id.maimage);
This way you will initialize the class variable instead of defining a new variable with the same name.
The same goes for all the other variables that you're defining again in the onCreate(...) method.
My method that is called (calculate BMI) inside of my activity is supposed to compute and display BMI (based on the formula inside the code), and display its value inside of a textview. The application runs correctly, however the value displayed is always zero. I am struggling to figure out if the problem lies in my formula (unlikely) or if the way that I am passing the value is incorrect. Any help would be appreciated. Code below
.Java file
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.widget.Toast;
public class Health extends ActionBarActivity {
EditText bloodPressure;
EditText cholesterol;
int weight;
int height;
EditText heightString;
EditText age;
TextView bmiText;
EditText weightString;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health);
weightString = (EditText) findViewById(R.id.weightTextBox);
heightString =(EditText) findViewById(R.id.heightTextBox);
bmiText = (TextView) findViewById(R.id.bmiTextView);
bloodPressure = (EditText) findViewById(R.id.bloodPressureTextBox);
cholesterol = (EditText) findViewById(R.id.cholesterolTextBox);
age = (EditText) findViewById(R.id.ageTextBox);
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void calculateBMI(View view)
{
weight = Integer.parseInt(weightString.getText().toString());
height = Integer.parseInt(heightString.getText().toString());
int BMI = 703 * (weight/(height*height));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Toast.makeText(Health.this, " Info Saved ", Toast.LENGTH_SHORT).show();
HealthInfo healthInfo = new HealthInfo(bloodPressure.getText().toString(),cholesterol.getText().toString(),heightString.getText().toString(),weightString.getText().toString(),age.getText().toString());
dbHandler.addHealth(healthInfo);
}
public void calorieClick(View view){
Intent i = new Intent(this, CalorieTracker.class);
startActivity(i);
}
public void openTips(View view){
Intent i = new Intent(this, HealthTipsActivity.class);
startActivity(i);
}
public void openPlans(View view){
Intent i = new Intent(this, DietPlansActivity.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_health, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
.XML file
<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="seniorproject.broncos.broncowellnessapp.Health"
android:background="#006699">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/blood_pressure_text"
android:id="#+id/bloodPressureTextView"
android:layout_alignParentTop="true"
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:text="#string/cholesterol_text"
android:id="#+id/cholesterolTextView"
android:layout_below="#+id/bloodPressureTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/weight_text"
android:id="#+id/weightTextView"
android:layout_below="#+id/cholesterolTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/height_text"
android:id="#+id/heightTextView"
android:layout_below="#+id/weightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/age_text"
android:id="#+id/ageTextView"
android:layout_below="#+id/heightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:width="150dp"
android:id="#+id/bloodPressureTextBox"
android:layout_below="#+id/bloodPressureTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/cholesterolTextBox"
android:layout_below="#+id/cholesterolTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/weightTextBox"
android:layout_below="#+id/weightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/heightTextBox"
android:layout_below="#+id/heightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/ageTextBox"
android:layout_below="#+id/ageTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/diet_plans_button_text"
android:onClick="openPlans"
android:id="#+id/dietPlansButton"
android:layout_below="#+id/ageTextBox"
android:layout_marginTop="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calorie_tracker_button"
android:id="#+id/calorieAccessButton"
android:layout_below="#+id/dietPlansButton"
android:onClick ="calorieClick"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/tips_button_text"
android:id="#+id/tipsButton"
android:onClick="openTips"
android:layout_below="#+id/calorieAccessButton"
android:layout_alignRight="#+id/calorieAccessButton"
android:layout_alignEnd="#+id/calorieAccessButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/BMI_button_text"
android:id="#+id/bmiButton"
android:onClick="calculateBMI"
android:layout_alignBottom="#+id/cholesterolTextBox"
android:layout_alignRight="#+id/dietPlansButton"
android:layout_alignEnd="#+id/dietPlansButton"
android:layout_marginRight="36dp"
android:layout_marginEnd="36dp"
android:background="#ff00b812" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Push Button to Compute BMI"
android:id="#+id/bmiTextView"
android:layout_alignBottom="#+id/weightTextBox"
android:layout_alignLeft="#+id/bmiButton"
android:layout_alignStart="#+id/bmiButton" />
</RelativeLayout>
Your weight and height variables are int. That is your problem. Change them to float or double
Currently, you are doing integer division which is causing the result to be truncated as follows: 1 / 2 gives 0
You are doing a division for integer which results mostly to zero.
That is why the result is always zero.
Change your weight and height variables to double like this
and just cast the result back to int.
double weight = 0.0;
double height = 0.0;
int BMI = (int)(703 * (weight/(height*height)));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Place this on the end of the onCreate() method:
findViewById(R.id.bmiButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weight = Integer.parseInt(weightString.getText().toString());
height = Integer.parseInt(heightString.getText().toString());
int BMI = 703 * (weight/(height*height));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Toast.makeText(Health.this, " Info Saved ", Toast.LENGTH_SHORT).show();
HealthInfo healthInfo = new HealthInfo(bloodPressure.getText().toString(),cholesterol.getText().toString(),heightString.getText().toString(),weightString.getText().toString(),age.getText().toString());
dbHandler.addHealth(healthInfo);
}
});
Some android version does not support onClick attribute for Button tag in XAML.
Im quite new to Android Dev, and well Programming also,
Im doing a Project for College by doing a Macro-Nutrient calculator which will give a user their Calorie needs for the day depending on their goal,
I have it almost finished (I will implement more features soon) Just want to get this basic feature done,
It all seems to work fine, but the textView named "displayValue" is not outputting the result,
Can someone please give me some advice?
ANDROID XML-LAYOUT
<?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:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="62dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:src="#drawable/bmr_logo" />
<EditText
android:id="#+id/weightInput"
android:layout_width="130dp"
android:layout_height="30dp"
android:layout_marginTop="175dp"
android:layout_marginLeft="75dp"
android:ems="10"
android:hint="#string/defaultText"
android:inputType="numberDecimal"
android:textSize="13sp" />
<Button
android:id="#+id/maintButton"
android:layout_width="75dp"
android:layout_height="30dp"
android:layout_marginTop="265dp"
android:layout_marginLeft="115dp"
android:text="Calculate"
android:textSize="12sp" />
<Button
android:id="#+id/bulkButton"
android:layout_width="75dp"
android:layout_height="30dp"
android:layout_marginTop="265dp"
android:layout_marginLeft="225dp"
android:text="Calculate"
android:textSize="12sp" />
<TextView
android:id="#+id/textView4"
android:layout_width="85dp"
android:layout_height="15dp"
android:layout_marginTop="250dp"
android:layout_marginLeft="220dp"
android:text="Gain Weight" />
<Button
android:id="#+id/cutButton"
android:layout_width="75dp"
android:layout_height="30dp"
android:layout_marginTop="265dp"
android:layout_marginLeft="15dp"
android:text="Calculate"
android:textSize="12sp" />
<EditText
android:id="#+id/heightInput"
android:layout_width="130dp"
android:layout_height="30dp"
android:layout_marginTop="135dp"
android:layout_marginLeft="75dp"
android:ems="10"
android:hint="#string/defaultText"
android:inputType="numberDecimal"
android:textSize="13sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="45dp"
android:layout_height="15dp"
android:layout_marginTop="180dp"
android:layout_marginLeft="15dp"
android:text="Weight:" />
<TextView
android:id="#+id/displayValue"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_marginTop="310dp"
android:layout_marginLeft="115dp"
android:textSize="12pt" />
<TextView
android:id="#+id/textView3"
android:layout_width="105dp"
android:layout_height="15dp"
android:layout_marginTop="250dp"
android:layout_marginLeft="105dp"
android:text="Maintain Weight" />
<TextView
android:id="#+id/textView1"
android:layout_width="75dp"
android:layout_height="15dp"
android:layout_marginTop="250dp"
android:layout_marginLeft="15dp"
android:text="Cut Weight" />
<EditText
android:id="#+id/ageInput"
android:layout_width="130dp"
android:layout_height="30dp"
android:layout_marginTop="90dp"
android:layout_marginLeft="75dp"
android:ems="10"
android:hint="#string/defaultText"
android:inputType="number"
android:textSize="13sp" />
<TextView
android:id="#+id/textHeight"
android:layout_width="45dp"
android:layout_height="15dp"
android:layout_marginTop="140dp"
android:layout_marginLeft="15dp"
android:text="Height:" />
<TextView
android:id="#+id/textAge"
android:layout_width="25dp"
android:layout_height="15dp"
android:layout_below="#+id/imageView1"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:text="Age:" />
</RelativeLayout>
JAVA CODE
package app.college.fitnessapp;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Macros extends Activity implements OnClickListener {
EditText ageInput;
EditText heightInput;
EditText weightInput;
Button cutButton;
Button maintButton;
Button bulkButton;
TextView displayValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.macro_layout);
// Find elements from the layout and Define them
ageInput = (EditText) findViewById(R.id.ageInput);
heightInput = (EditText) findViewById(R.id.heightInput);
weightInput = (EditText) findViewById(R.id.weightInput);
cutButton = (Button) findViewById(R.id.cutButton);
maintButton = (Button) findViewById(R.id.maintButton);
bulkButton = (Button) findViewById(R.id.bulkButton);
displayValue = (TextView) findViewById(R.id.displayValue);
//Set button listeners
cutButton.setOnClickListener(this);
maintButton.setOnClickListener(this);
bulkButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int ageNum = 0;
int weightNum = 0;
int heightNum = 0;
int result = 0;
int calculate = 0;
int percentAdd = 0;
// Test to see if fields are empty
if (TextUtils.isEmpty(ageInput.getText().toString())
|| TextUtils.isEmpty(heightInput.getText().toString())
|| TextUtils.isEmpty(weightInput.getText().toString())) {
return;
}
// This is to read the Edit Text fields from the layout and fill the Variables with Numbers
ageNum = Integer.parseInt(ageInput.getText().toString());
weightNum = Integer.parseInt(weightInput.getText().toString());
heightNum = Integer.parseInt(heightInput.getText().toString());
//Defines which button has been clicked and will calculate accordingly
switch (v.getId()) {
case R.id.cutButton:
calculate = (10*weightNum) + (6*heightNum) - (5*ageNum) + 5;
percentAdd = (calculate*1);
result = calculate + percentAdd;
break;
case R.id.maintButton:
calculate = (10*weightNum) + (6*heightNum) - (5*ageNum) + 5;
percentAdd = (calculate*1);
result = calculate + percentAdd;
break;
case R.id.bulkButton:
calculate = (10*weightNum) + (6*heightNum) - (5*ageNum) + 5;
percentAdd = (calculate*1);
result = calculate + percentAdd;
break;
default:
break;
}
//Displays the output
displayValue.setText(String.valueOf(result));
}
}
I have a feeling it is the last line with the displayValue output,
This Problem is Solved...
If i make my variables such as ageNum, weightNum etc into floats and parse the string into a Float i then get this error "The method setText(CharSequence) in the type TextView is not applicable for the arguments (float)"
But if I define them as Ints and parse the strings to Int i then get no error messgage but no output,
I would prefer to output as a float though, just incase a user would enter their weight at 78.5 or something,
This is my only problem now,
Im not getting any outputs :( in the displayValue Textview
Any suggestions please?
Thanks in advance!
then get this error "The method setText(CharSequence) in the type
TextView is not applicable for the arguments (float)"
You have to use the setText() method that accepts an object which implements the CharSequence interface (i.e like the String class). You can use the static method String.valueOf(float value).
displayValue.setText(String.valueOf(result));
The setText(...) takes as an argument a java.lang.CharSequence (e.g. a java.lang.String). You are passing an int.
Check out the String class for converting literals like int to String.