Input Validation not working android studio - java

For some reason my input Validation is not working. Every time I put calculate it crashes "app" when it should have an error saying that I need to input height/weight. When I do input the numbers it does calculate. Thanks for the help :). I'm new to android studio .
here is my calculation java file
public class BmiFrag extends Fragment implements View.OnClickListener {
Button BmiButton;
private double weight1=0;
private double height1=0;
public static EditText heightIn;
public static EditText weightIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_bmi, container, false);
BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
BmiButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.CalculateBmi:
weightIn = (EditText)
getActivity().findViewById(R.id.ETtweight);
heightIn = (EditText) getActivity().findViewById(R.id.ETHeight);
final TextView tv4 = (TextView)
getActivity().findViewById(R.id.TFDisplayBmi);
String str1 = weightIn.getText().toString();
String str2 = heightIn.getText().toString();
float weight = Float.parseFloat(str1);
float height = Float.parseFloat(str2) ;
float bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}
break;
}
}
private float calculateBMI(float weight, float height) {
float bmi= (float) (weight/ (height*height)*4.88);
float total= Math.round(bmi);
return total;
}
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
}
#Override
public void onDetach() {
super.onDetach();
}
}

Try to change the code like the following,
if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}else{
float weight = Float.parseFloat(str1);
float height = Float.parseFloat(str2) ;
float bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
}

if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}

firstly, sort your indentation and variable names out. Never name a variable str1, str2: always meaningful names. Indentation should always be consistent. This will help out but fixing in the future for readability and speed.
You're doing input validation after you actually input and assign things through
calculateBMI() method
That part of your code reads: Lets take text from text fields, interpret the BMI and then see if the textfields are empty

Related

infinity double operation resulting in infinity java/android studio

I'm trying to do a division (double/double) and the result is Infinity. Can someone help me and explain why that's happening?
I searched some forums, but I didn't get the answer.
I have something like that:
public class CalculoSapIsolada extends AppCompatActivity
{
double areaAcoX;
double numeroBarrasX;
double areaBarraX;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculo_sap_isolada);
//Here is where i get the value of areaBarraX
if(SapataIsolada.getAço()==50)
{
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner_diametro_aço_x);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.diametro_aço_CA_50, android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
staticSpinner.setPrompt("Selecione o diâmetro da armadura");
staticSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
Object item = adapterView.getItemAtPosition(i);
if (i == 0) {
diametroAçoX = 0.5;
areaBarraX = 0.196;
}
if (i == 1) {
diametroAçoX = 0.63;
areaBarraX = 0.31;
}
if (i == 2) {
diametroAçoX = 0.8;
areaBarraX = 0.5;
}
if (i == 3) {
diametroAçoX = 1;
areaBarraX = 0.785;
}
if (i == 4) {
diametroAçoX = 1.25;
areaBarraX = 1.22;
}
if (i == 5) {
diametroAçoX = 1.6;
areaBarraX = 2.01;
}
if (i == 6) {
diametroAçoX = 2;
areaBarraX = 3.14;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
/* the value of areaAcoX is calculated previously and during the testrun it receives areaAcoX=11.36016 and the value of areaBarraX=0.5 */
numeroBarrasX=areaAcoX/areaBarraX;
Button calcular =(Button)findViewById(R.id.calcular_resultado);
calcular.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//in altura.setText, areaAcoX==11.36016
TextView altura = (TextView)findViewById(R.id.alturaTotal);
altura.setText(""+areaAcoX);
//In ladoLtopo.setText, areaBarraX==0.5
TextView ladoLtopo = (TextView)findViewById(R.id.ladoL_topo);
ladoLtopo.setText(""+areaBarraX);
//In numBarrasX.setText, numeroBarrasX==Infinity
TextView numBarrasX = (TextView)findViewById(R.id.numeroBarras_x);
numBarrasX.setText(""+numeroBarrasX);
});
}
}
I have some similar operations in the code that is not shown here and I didn't get the infinity error in their value.
Dividing by 0.0 of type double yields infinity. Perhaps there's a divide by 0.0 at this line before areaBarraX has been initialized:
numeroBarrasX=areaAcoX/areaBarraX;

android: calculate double percentage?

I want to calculate percentage. But it's giving me wrong result(2.78674E7).
Following's my code:
public class DetailActivity extends AppCompatActivity {
private Button btn_pre_payment;
private EditText et_pre_payment;
private double monthlyPayment;
private double allPayment = 139337000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
btn_pre_payment = (Button)findViewById(R.id.bt_prepayment);
et_pre_payment = (EditText)findViewById(R.id.et_prepayment);
btn_pre_payment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(et_pre_payment.getText().length() > 0){
float value = Float.valueOf(et_pre_payment.getText().toString());
if(value >= 10){
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(et_pre_payment.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
**monthlyPayment = (allPayment / 100f) * value;
tvMonthlyPaymentH.setText(String.valueOf(monthlyPayment));
remainderPayment -= monthlyPayment;**
}
} else Toast.makeText(DetailActivity.this, "Low is 10%!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DetailActivity.this, "Enter value!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Why can't it calculate correct result? It gives me 2.78674E7. I want to calculate percentage.
For starters, your math is wrong. It should be value/total*100, not value*total/100.
The value is given in scientific notation you can try using
String.format("%.0f", YourValue)
to get correct value .
check out this question and this question

Conditional Spinner

I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userEcts = (EditText) findViewById(R.id.ects_input);
summary = (TextView) findViewById(R.id.text_summary);
courses = (Spinner) findViewById(R.id.course_spinner);
calculateBtn = (Button) findViewById(R.id.calculate);
calculateBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calculate method.
calculate();
}
});
final String[] courseArray = new String[4];
{
courseArray[0] = "Preddiplomski studij Menadžment";
courseArray[1] = "Preddiplomski studij Promet";
courseArray[2] = "Preddiplomski Upravni studij";
courseArray[3] = "Specijalistički studij Menadžment";
}
ArrayAdapter courseAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, courseArray);
courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
courses.setAdapter(courseAdapter);
courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from Spinner and store in string conductorSize........
cors = parent.getItemAtPosition(pos).toString();
if (cors.equals(0)) {
ectsPrice.setText("200");
price = 200;
} else if (cors.equals(1)) {
ectsPrice.setText("250");
price = 250;
} else if (cors.equals(2)) {
ectsPrice.setText("300");
price = 300;
} else if (cors.equals(3)) {
ectsPrice.setText("350");
price = 350;
} else {
//Do nothing
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
public void calculate() {
//gets entered text from the EditText,and convert to integers.
if (!TextUtils.isEmpty(userEcts.getText().toString())) {
Double ects = Double.parseDouble(userEcts.getText().toString());
//do the calculation
Double calculatedPrice = ects * price;
//set the value to the TextView, to display on screen.
summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
} else {
Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
calculate();
}
}
So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?
Use the position number to check the condition.
String[] courseArray = new String[4];
{
courseArray[0] = "Preddiplomski studij Menadžment";
courseArray[1] = "Preddiplomski studij Promet";
courseArray[2] = "Preddiplomski Upravni studij";
courseArray[3] = "Specijalistički studij Menadžment";
}
ArrayAdapter courseAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, courseArray);
courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
courses.setAdapter(courseAdapter);
courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from Spinner and store in string conductorSize........
cors = parent.getItemAtPosition(pos).toString();
if (cors.equals(courseArray[0])) {
ectsPrice.setText("200");
price = 200;
} else if (cors.equals(courseArray[1])) {
ectsPrice.setText("250");
price = 250;
} else if (cors.equals(courseArray[2])) {
ectsPrice.setText("300");
price = 300;
} else if (cors.equals(courseArray[3])) {
ectsPrice.setText("350");
price = 350;
} else {
//Do nothing
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
Use a switch statment :
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
switch(pos){
case 0:
ectsPrice.setText("200");
price = 200;
break;
case 1:
ectsPrice.setText("250");
price = 250;
break;
case 2:
ectsPrice.setText("300");
price = 300;
break;
case 3:
ectsPrice.setText("350");
price = 350;
break;
}
}

Set empty edittext value to zero

I have created a simple program to try to figure out how to do this. it has two edit text fields (input type number decimal), a text view and a button. I want the sum of the two input fields to be displayed in the text view when the user hits the button. can someone tell me how to set the value of one edit text field to zero if the user left it blank? I have tried many ways but nothing worked.
Edit: i want to achieve this while keeping the hint of edit text as before (without changing the value to zero like " setText("0"); ".
here's my java code (tell me what to add)
package com.example.android.testedittexttozero;
import...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v) { //the button
final EditText number1 = (EditText) findViewById(R.id.numberFirst);
EditText number2 = (EditText) findViewById(R.id.numberSecond);
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
Do you know that in java if you dont initialize a variable with a default value, it's default value be 0?
in short:
try {
int a;//by default, it will be 0;
int b = Integer.parseInt(number2.getText().toString());//let it be 2
int sum = a + b;
total.setText("" + sum);//Ans will be 2 only
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
If you don't enter any value in a, it will be set to as 0. Like if you leave a blank, and enter 2 in second edittext, the ans will be two nevertheless..
public void ZeroingEmpytEditText() {
int f= 0; // Zeroing Factor
if (number1.getText().toString().length() > 0) {
a = Integer.parseInt(number1.getText().toString());
} else {
a=f;
}
if (number2.getText().toString().length() > 0) {
b = Integer.parseInt(number2.getText().toString());
} else {
b=f;
}
int sum = a + b ;
total.setText(sum + "");
}
you can set value 0 of edit text in oncreate method.
like,
public class MainActivity extends AppCompatActivity {
EditText number1,number2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.numberFirst);
number2 = (EditText) findViewById(R.id.numberSecond);
number1.settext("0");
number2.settext("0");
}
public void calculate(View v) { //the button
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
its helpfull for you.

My Calculations are off when Creating a BMI Calculator

Problem: My Calculations are off when I compared the results on my app to the bmi website. THank you so much in advance, also my math is really bad so I apologize in advance.
Here are the results that my app is giving me:
http://www.tiikoni.com/tis/view/?id=8bd04d4
Here are the results based of the BMI Website NIH
http://www.tiikoni.com/tis/view/?id=86d4458
BMIFRAG.java
public class BmiFrag extends Fragment implements View.OnClickListener
{
Button BmiButton;
public static EditText heightFT;
public static EditText heightIn;
public static EditText weightIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_bmi, container,
false);
BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
BmiButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.CalculateBmi:
weightIn = (EditText)
getActivity().findViewById(R.id.ETtweight);
heightIn = (EditText)
getActivity().findViewById(R.id.ETHeightIn);
heightFT = (EditText)
getActivity().findViewById(R.id.ETHeightFT);
final TextView tv4 = (TextView)
getActivity().findViewById(R.id.TFDisplayBmi);
String getWeightIN = weightIn.getText().toString();
String getHeightIN = heightIn.getText().toString();
String getHeightFT = heightFT.getText().toString();
if (TextUtils.isEmpty(getWeightIN)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(getHeightIN)) {
heightIn.setError("Please enter your height in Inches");
heightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(getHeightFT)) {
heightFT.setError("Please enter your height in Feet");
heightFT.requestFocus();
return;
}
else {
float weight = Float.parseFloat(getWeightIN );
float heightIN = Float.parseFloat(getHeightIN) ;
float heightFT = Float.parseFloat(getHeightFT) ;
float bmiValue = calculateBMI(weight,heightIN,heightFT);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" +
bmiInterpretation));
}
break;
}
}
private float calculateBMI(float weight, float heightIN, float v) {
float bmi= (float) (weight/ (heightIN*v)*4.88);
float total= Math.round(bmi);
return total;
}
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
You don't use the same formula. Try this:
float bmi = weight * 703f / (float)Math.pow(heightIN+12f*v,2);
The formula above can be found here.
I hope it helps.

Categories