Source Code Check Please - Macro Nutrient Calculator - java

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.

Related

Function not called when clicking on a button in Android

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.

Android emulator doesn't take input

I wanted to create an android app that adds two number.
Firstly i set up the Layout design.
Secondly in the main_activity file i wrote the code.
This is my code:
package com.example.asus.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
double num1,num2, sum;
EditText firstNumber;
EditText secondNumber;
TextView addResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
//TextView addResult;
Button btnAdd;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstNumber = (EditText)findViewById(R.id.editText);
secondNumber = (EditText)findViewById(R.id.editText2);
addResult = (TextView)findViewById(R.id.textView4);
btnAdd = (Button)findViewById(R.id.button);
//Button button = (Button)findViewById(R.id.button);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1 = Double.parseDouble(firstNumber.getText().toString());
//num1 = Double.parseDouble(firstNumber.getText().toString());
num2 = Double.parseDouble(secondNumber.getText().toString());
//num2 = Double.parseDouble(secondNumber.getText().toString());
sum = num1 + num2;
//sum = num1 + num2;
addResult.setText(Double.toString(sum));
// addResult.setText(Double.toString(sum));
}
});
}
}
my code has no errors, however when i run the android emulator it doesn't take any input.
when i click on letter or number, the cursor moves a step, but no input is shown.
I have tried those solutions that i have found, but none has worked for me:
From advanced settings, check enable keyboard input.
From AVD, create a virtual device, hardware profile, check has hardware keyboard input.
Add in config file hw.keyboard=yes
However none of them worked for me, where is the error exactly?
This is my Layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".MainActivity">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:text="First Number"
app:layout_constraintBottom_toBottomOf="#+id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/editText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:text="Second Number:"
app:layout_constraintBottom_toBottomOf="#+id/editText2"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="33dp"
android:layout_marginLeft="33dp"
android:text="Result:"
app:layout_constraintBottom_toBottomOf="#+id/editText3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/editText3" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_marginTop="103dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="87dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:text="ADD"
app:layout_constraintStart_toEndOf="#+id/textView2"
app:layout_constraintTop_toBottomOf="#+id/editText2" />
</android.support.constraint.ConstraintLayout>
show your XML code , it might be :
1- you set a custom input type for Edit Text;
2- your windows/Ubuntu/mac is on a unsupported keyboard language for emulator;
3- in emulator advanced settings keyboard input is disabled ;
The height of the EditText are too small to display the text. So increase the height of those views or change it into wrap_content.

(Android)Trying to understand why my method will not compute/display the correct value in the textview

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.

Java physics triangles

okay, i cannot post images yet :/
Basically, i have an application with three edittext fields, three check boxes, a calculation button and a text field to output the answer. i want the program to scan to see which value is missing, so that from this it know which calculation it should do. Another method would be for the user to check one of the checkbox's and then the program would only run the calculation for the corresponding checkbox.
for instance, if the user inputs Q = 10, T = 2, and checks the checkbox for I, the program would then do the math and display I = 20 ?
this make much sense yet
i spose in psuedo code it would look like
" if checkbox one is checked and values for Q and T have been entered, then calculate value for I and display in answers field" however i will be adding some error checks and validation methods in there.
if you need the xml file and java file then please ask, im just looking for a method at the moment as to how i could do it, i wouldnt expect you all to waste your free time writing a whole program for me.
cheers guys and girls
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background1"
android:gravity="fill"
android:orientation="vertical"
android:textColor="#ffffff"
tools:context=".CurrentPage" >
<!--
The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc.
-->
<!--
This FrameLayout insets its children based on system windows using
android:fitsSystemWindows.
-->
<TextView
android:id="#+id/Current_hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_marginTop="33dp"
android:text="Welcome to the Current Calculation page."Hint - Use the check boxes to find the values that are missing "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/Equation_letter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/current_calculate"
android:layout_marginTop="37dp"
android:layout_toLeftOf="#+id/current_calculate"
android:text=" HELLO "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/Distances_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Equation_letter"
android:layout_alignBottom="#+id/Equation_letter"
android:layout_alignLeft="#+id/current_calculate"
android:layout_alignParentRight="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Q"
android:layout_alignRight="#+id/Q"
android:layout_below="#+id/Q"
android:layout_marginTop="36dp"
android:gravity="right|top"
android:text="t ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<CheckBox
android:id="#+id/custom3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/t"
android:layout_alignLeft="#+id/custom2"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<CheckBox
android:id="#+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/number_input_3"
android:layout_alignLeft="#+id/custom3"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Current_hint"
android:layout_alignRight="#+id/Current_hint"
android:layout_below="#+id/Equation_letter"
android:layout_marginTop="25dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/CurrentmainHelp"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1.31"
android:text="HELP! This equation can be used to calculate the current of an object in amps. The correct equation to discover amps is I=Q/t. Where I = current, Q = charge flowing past a point in the circuit, and t = time taken for the charge to flow. Please note, Q is measure in coulombs and t is measured in seconds, with I being measured in amperes.
Still need more help? "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/Yes_Please"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="36dp"
android:layout_weight="1.31"
android:onClick="CurrentHelp"
android:text="Yes Please"
android:textColor="#ffffff" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/current_calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Calculate_Current"
android:textColor="#ffffff"
/>
<EditText
android:id="#+id/number_input_2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_above="#+id/t"
android:layout_alignLeft="#+id/number_input_1"
android:layout_alignRight="#+id/number_input_1"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:textColor="#ffffff" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/number_input_3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/t"
android:layout_alignLeft="#+id/number_input_2"
android:layout_alignRight="#+id/number_input_2"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:textColor="#ffffff" />
<CheckBox
android:id="#+id/custom2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/number_input_1"
android:layout_marginLeft="45dp"
android:layout_toRightOf="#+id/number_input_1"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<EditText
android:id="#+id/number_input_1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/Q"
android:layout_alignRight="#+id/current_calculate"
android:ems="10"
android:focusable="false"
android:inputType="numberDecimal"
android:singleLine="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/Q"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Equation_letter"
android:layout_below="#+id/I"
android:layout_marginTop="36dp"
android:gravity="right|top"
android:text="Q ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/I"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Q"
android:layout_alignRight="#+id/Q"
android:layout_below="#+id/Current_hint"
android:layout_marginTop="65dp"
android:gravity="right|top"
android:text="I ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
okay, that was the xml, and this is the java so far
package com.kieran.whetherfieldphysicscalculator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
// i=q/t this will be the first calculation on the list
public class Current extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
// Show the Up button in the action bar.
setupActionBar();
Button calc1 = (Button)findViewById(R.id.current_calculate);
calc1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
}
public void CurrentHelp(View view) {
// Do something in response to button
Intent intent = new Intent(this, CurrentHelp.class);
startActivity(intent);
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am asking if there is an easier way to formate the program to find the values, rather than have to code each individual segment?
cheers
In your case I guess that you want the user to check only one checkbox and only answer corresponding to that checkbox should be displayed to the user.
so for that you would need to set OnClickListener on checkbox so that the corresponding operation is selected.
Read here on how to set listener on checkbox and use it. Paticularly look for the addListenerOnChkIos() method as it has the code you want.
Also set another OnClickListener on the calculate button and in that check which checkbox is checked depending on which you will perform the operation and update the textview.

NullPointerException in Android Program in onCreate()

I am fairly new to android and am writing an app that will solve physics problems. The math is going well thanks to some help from these forums, but when I try to start my activity from a list it comes up with a nullpointerexception in the onCreate Method of the new activity. This doesn't seem to make much sense though, because all thats there is a submit button that executes the math from some EditText views. Here is my code.
package android.physicsengine;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.lang.Math;
public class ProjectileMotion extends Activity {
private EditText acceleration;
private EditText finalVelocity;
private EditText initialVelocity;
private EditText time;
private EditText deltay;
private EditText velocity;
private EditText deltax;
private Button submitButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projectile_motion_layout);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
acceleration = (EditText)findViewById(R.id.acceleration);
double a = Doublify(acceleration);
finalVelocity = (EditText)findViewById(R.id.finalVelocity);
double vf = Doublify(finalVelocity);
initialVelocity = (EditText)findViewById(R.id.intitialVelocity);
double vi = Doublify(initialVelocity);
time = (EditText)findViewById(R.id.time);
double t = Doublify(time);
deltay = (EditText)findViewById(R.id.deltay);
double y = Doublify(deltay);
velocity = (EditText)findViewById(R.id.velocity);
double vx = Doublify(velocity);
deltax = (EditText)findViewById(R.id.deltax);
double x = Doublify(deltax);
//Y Axis
if(time.getText()==null && deltay.getText()==null){
time.setText(Double.toString((vf-vi)/a));
deltay.setText(Double.toString(((vf-vi)/a)+(a*Math.pow(((vf-vi)/a),2))));
}
if(acceleration.getText()==null && deltay.getText()==null){
acceleration.setText(Double.toString((vf-vi)/t));
deltay.setText(Double.toString((vi*t+.5*((vf-vi)/t))*Math.pow(t,2)));
}
if(acceleration.getText()==null && time.getText()==null){
acceleration.setText(Double.toString(((Math.pow(vf,2)-Math.pow(vi,2)))/2*y));
time.setText(Double.toString(2*y*(vf-vi)/(Math.pow(vf,2)-vi)));
}
if(initialVelocity.getText()==null && deltay.getText()==null){
initialVelocity.setText(Double.toString(vf-a*t));
deltay.setText(Double.toString((vf-a*t)*t+.5*a*Math.pow(t,2)));
}
if(initialVelocity.getText()==null && time.getText()==null){
initialVelocity.setText(Double.toString(Math.sqrt(Math.pow(vf,2)-2*a*y)));
time.setText(Double.toString((vf-Math.sqrt(Math.pow(vf,2)-2*a*y))/2));
}
if(initialVelocity.getText()==null && acceleration.getText()==null){
initialVelocity.setText(Double.toString(vf-2*(vf-y/t)));
acceleration.setText(Double.toString((2/t)*(vf-y/t)));
}
if(finalVelocity.getText()==null && deltay.getText()==null){
finalVelocity.setText(Double.toString(vi+a*t));
deltay.setText(Double.toString(vi*t+.5*a*Math.pow(t,2)));
}
if(finalVelocity.getText()==null && time.getText()==null){
finalVelocity.setText(Double.toString(Math.sqrt(Math.pow(vi,2)+2*a*y)));
time.setText(Double.toString(((Math.sqrt(Math.pow(vi,2)+2*a*y)-vi))/a));
}
if(finalVelocity.getText()==null && acceleration.getText()==null){
acceleration.setText(Double.toString(2*(y-vi*t)/Math.pow(t,2)));
finalVelocity.setText(Double.toString(vi+(2*(y-vi*t)/t)));
}
if(finalVelocity.getText()==null && initialVelocity.getText()==null){
initialVelocity.setText(Double.toString((y-.5*a*Math.pow(t,2))/t));
finalVelocity.setText(Double.toString((y-.5*a*Math.pow(t,2))/t)+a*t);
}
}
});
}
private double Doublify(EditText editText){
if(editText.getText()!= null){
return Double.parseDouble(editText.getText().toString());
}
return 0;
}
}
and the XML
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TableRow>
<TextView android:text="Projectile Motion Engine"
android:textSize="25dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_span="4"
android:layout_gravity="center" />
</TableRow>
<TableRow>
<TextView android:text="X axis"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_span="2"
android:textStyle="bold"/>
<TextView android:text="Y axis"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_span="2"
android:textStyle="bold"/>
</TableRow>
<TableRow>
<TextView android:text="accel(m/s^2)="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/acceleration"
android:text="9.8"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:text="deltax(m)="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/deltax"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView android:text="init v(m/s)="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/intitialVelocity"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:text="v ="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/velocity"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView android:text="final v(m/s)="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/finalVelocity"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:text="time(s)="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/time"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView android:text="deltay(m)="
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="#+id/deltay"
android:inputType="numberDecimal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button android:id="#+id/submitButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_span="2"
android:text="Launch" />
</TableRow>
</TableLayout>
super.onCreate(savedInstanceState);
setContentView(R.layout.projectile_motion_layout);
submitButton.setOnClickListener(new OnClickListener() {
You forgot to assign your submitButton (with findViewById)
super.onCreate(savedInstanceState);
setContentView(R.layout.projectile_motion_layout);
submitButton = (Button) findViewById((R.id.submitButton); // new line
submitButton.setOnClickListener(new OnClickListener() {
Based on the code you've posted, it appears that you call
submitButton.setOnClickListener(new OnClickListener() {
before instantiating submitButton with a value. This would cause a NullPointer
projectile_motion_layout may not be in your android manifest. I would check that first.
You can find the Application Nodes under the Application tab in the manifest.

Categories