Android empty editText is crashing my program [duplicate] - java

This question already has answers here:
How to parse a double from EditText to TextView? (Android)
(9 answers)
Closed 6 years ago.
First time into Java and I'm trying to create a simple tips calculator for my coworkers at the restaurant I work for, but when I leave one of the editText fields empty the program crashes.
MainACtivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalTipsInput = (EditText) findViewById(R.id.totalTipsInput);
waiter1Hours = (EditText) findViewById(R.id.waiter1Hours);
waiter2Hours = (EditText) findViewById(R.id.waiter2Hours);
waiter3Hours = (EditText) findViewById(R.id.waiter3Hours);
waiter4Hours = (EditText) findViewById(R.id.waiter4Hours);
tipsPerHourView = (TextView) findViewById(R.id.tipsPerHourView);
totalHoursView = (TextView) findViewById(R.id.totalHoursView);
barsCutView = (TextView) findViewById(R.id.barsCutView);
waiter1Pay = (TextView) findViewById(R.id.waiter1Pay);
waiter2Pay = (TextView) findViewById(R.id.waiter2Pay);
waiter3Pay = (TextView) findViewById(R.id.waiter3Pay);
waiter4Pay = (TextView) findViewById(R.id.waiter4Pay);
taxDepositView = (TextView) findViewById(R.id.taxDepositView);
Button calcBtn = (Button) findViewById(R.id.calcBtn);
calcBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
double cWaiter1Hours = Double.parseDouble(waiter1Hours.getText().toString());
double cWaiter2Hours = Double.parseDouble(waiter2Hours.getText().toString());
double cWaiter3Hours = Double.parseDouble(waiter3Hours.getText().toString());
double cWaiter4Hours = Double.parseDouble(waiter4Hours.getText().toString());
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double resultBarsCut = (totalTips * 7) / 100;
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
taxDepositView.setText(Double.toString(resultTaxDeposit));
}
});
}
Tried to do something like this but got an error with .length():
if (double totalTips = Double.parseDouble(totalTipsInput.getText().toString()).length() < 1 || totalTipsInput = null) {
totalTips = 0
} else {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
}

Use this method in your class:
public static Double returnDouble(EditText editText)
{
try {
if(editText.getText().toString().isEmpty())
{
return 0d;
}
else
{
return Double.parseDouble(editText.getText().toString());
}
} catch (NumberFormatException e) {
return 0d;
}
}

You can do something like this to make sure that the input to the "parseDouble" is valid:
double totalTips = 0;
Editable totalString = totalTipsInput.getText();
if(totalString.length() > 0){
totalTips = Double.parseDouble(totalString.toString());
}
If the "totalTips" field can take user input you need to make sure they can only enter a valid number. The lazy way might be to put a try/catch around the parseDouble as well, and handle the case where someone may enter something that can't be parsed to a double (ie, empty string, letters, malformed numerical value)
I would recommend not trusting users to always input valid values in the rest of the waiter hours fields as well. You would want to do similar checks on those fields before attempting to parse the input.

Related

Ignore empty calculation errors originating from empty cells

I'm trying to make formulas using text entries for multiple rows only if they have entries though. The problem is it errors out if one of the editText boxes is empty.
Is there a way to ignore the errors and carry on with the rest of the script? Doing calculations if the entries exist?
There are a total of 3 columns with 6 rows for entries. Each of the 3 entries per row should be filled, but if an entry isn't, I don't want it to calculate for that row or have the answer come up as 0.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
e11 = (EditText) findViewById(R.id.editTextTextPersonName3);
e12 = (EditText) findViewById(R.id.editTextTextPersonName4);
e13 = (EditText) findViewById(R.id.editTextTextPersonName5);
t11 = (TextView) findViewById(R.id.textView8);
e14 = (EditText) findViewById(R.id.editTextTextPersonName6);
e15 = (EditText) findViewById(R.id.editTextTextPersonName8);
e16 = (EditText) findViewById(R.id.editTextTextPersonName7);
t12 = (TextView) findViewById(R.id.textView9);
}
public void CalculateMol(View v) {
float entry11 = Float.parseFloat((e11.getText().toString()));
float entry12 = Float.parseFloat((e12.getText().toString()));
float entry13 = Float.parseFloat((e13.getText().toString()));
float result8 = (entry11 * entry12 * entry13/1000000);
t11.setText(String.valueOf(result8+"g"));
float entry14 = Float.parseFloat((e14.getText().toString()));
float entry15 = Float.parseFloat((e15.getText().toString()));
float entry16 = Float.parseFloat((e16.getText().toString()));
float result12 = (entry14 * entry15 * entry16/1000000);
t12.setText(String.valueOf(result12+"g"));
You need to check that your editText values are Empty or not before calculation.
So inside your CalculateMol Method; first validate your input string using this method:
public static boolean isEmptyStr(String Val) {
if (Val == null || Val.isEmpty() || Val.trim().isEmpty() || Val.equalsIgnoreCase("null"))
return true;
else
return false;
}
use above method like this;
public void CalculateMol(View v) {
float entry11;
if(!isEmptyStr(e11.getText().toString())){
entry11 = Float.parseFloat((e11.getText().toString()));
}
}
then apply your calculations.

How to make Toast pop up if EditText field is empty or the inputted value is equal to 0?

First of all, I'm new to Android Studio. I'm currently trying to make a BMI calculator app where the user has to enter their weight and height and select the unit of measurement used for both. A Toast message (R.string.toastError) should pop up upon clicking a button if: (1-2) the EditText fields for weight and height are empty and (3) if the value of HeightInput is less than or equal to zero; else, the calculation should proceed.
The whole math part worked fine when I tested it, but when I left the fields blank, the app just crashes. The Toast pops up though when HeightInput = 0, but not when the EditText field for Weight is left empty at the same time. I think it's the way I wrote the 'if' statement that's giving me a problem.
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
Here's the whole code for reference:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// weight units spinner
final Spinner spinWeightUnit = (Spinner) findViewById(R.id.spinnerWeightUnit);
spinWeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> WeightList = ArrayAdapter.createFromResource(this, R.array.WeightUnits, android.R.layout.simple_spinner_item);
WeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinWeightUnit.setAdapter(WeightList);
// height units spinner
final Spinner spinHeightUnit = (Spinner) findViewById(R.id.spinnerHeightUnit);
spinHeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> HeightList = ArrayAdapter.createFromResource(this, R.array.HeightUnits, android.R.layout.simple_spinner_item);
HeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinHeightUnit.setAdapter(HeightList);
// calculate button
Button buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
// weight conversion constant
if (finalWeightUnit.equals("kilograms")) {
constantWeight = 1.00;
} else {
constantWeight = 1 / 2.204623;
}
// height conversion constant
switch (finalHeightUnit) {
case "inches":
constantHeight = 0.0254;
break;
case "centimeters":
constantHeight = 0.01;
break;
case "feet":
constantHeight = 1 / 3.2808;
break;
default:
constantHeight = 1.00;
break;
}
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'd appreciate any help! Thanks!
Try below in if statement
if (editTextWeightInput.getText().toString().trim().isEmpty() || editTextHeightInput.getText().toString().trim().isEmpty() || HeightInput <= 0)
When you leave an EditText Empty the getString() function returns a null value. First you need to check for null in the if condition.
if (editTextWeightInput.getText() == null || editTextWeightInput.getText().toString().length() == 0 || HeightInput <= 0)
You need to validate your declaration code also.
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
if(TextUtil.isEmpty(editTextWeightInput.getText().toString())||TextUtil.isEmpty(editTextHeightInput.getText().toString())){
Toast.makeText(getApplicationContext(), R.string.toastError,
Toast.LENGTH_SHORT).show();
}else{
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
}

How to count sum total in Java using Android Studio

I just learned Java using Android Studio.
My code error for use integer to count sum.
I try to decode string to integer but still error.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtvalue = (EditText) findViewById(R.id.value);
final Spinner edtjw = (Spinner) findViewById(R.id.spinner1);
txtpa = (TextView) findViewById(R.id.pa);
txttotal = (TextView) findViewById(R.id.total);
btncount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String value = edtvalue.getText().toString().trim();
String jw = edtjw.getSelectedItem().toString().trim();
double h = Double.parseDouble(value);
double j = Double.parseDouble(jw);
String numbertostring = String.format ("%.2f", (0.02*h));
String numbertostring2 = String.format ("%.2f", (0.025*h));
String numbertostring3 = String.format ("%.2f", (0.0275*h));
if (j == 1){
txtpa.setText(numbertostring);
} else if (j ==2){
txtpa.setText(numbertostring);
} else if (j ==3){
txtpa.setText(numbertostring);
} else if (j ==4){
txtpa.setText(numbertostring2);
} else if (j ==5){
txtpa.setText(numbertostring3);
} else {
txtpa.setText(0);
}
int tot = (h*j)+txtpa;
txttotal.setText("Total : " + tot);
}}
By looking at the code snippet, you should get string value from txtpa which is of type TextView, then parse it into double
double tot = (h*j)+Double.parseDouble(txtpa.getText().toString());
as mentioned in the above comment by Naitik Soni.

java.lang.NumberFormatException: Invalid int: “” [duplicate]

This question already has answers here:
Edit Text shows exception Invalid Int ""
(5 answers)
Closed 6 years ago.
I am getting java.lang.NumberFormatException: Invalid int: error
I believe the declarations are appropriate
I have taken input of numbers in string earlier itself.
The below part only calculates the sum.
Second part is a continuation of 1st part.
Declaration is given below:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num1 = (EditText)findViewById(R.id.num1);
final EditText num2 = (EditText)findViewById(R.id.num2);
final EditText resu = (EditText)findViewById(R.id.resu);
resu.setFocusableInTouchMode(false);
resu.setFocusable(false);
resu.setClickable(false);
final Button plus = (Button)findViewById(R.id.plus);
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
On click program:
plus.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View view) {
try{
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
}catch(Exception e){
resu.setText(""+e);
}
}
);
Move the following code inside your onlick() method, because in your oncreate() if the EditText is empty it will return empty String (""), so you need to get the value when the button is clicked, not before it:
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
To:
plus.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try {
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
} catch(Exception e) {
resu.setText(""+e);
}
}
});
Problem lies on Integer Object to float primitive type conversion. I think if you give an input a Whole Number then your code should work fine. code
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
But if it's not a whole Number then inorder to incounter NumberFormatException you're failing to convert String into your appropriate primitive Data type.
And also check for empty String ("") in n1 and n2 by if(n1=="")
plus.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try
{
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
if(n1==""){
n1="0";
}
float sum = Float.valueOf(n1) + Float.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
}
catch(Exception e)
{
resu.setText(""+e);
}
}
});

How to pass data from a class and used in another class for calculation

i'm trying to do this feature where i calculate the calories needed in BMIcalculation class, then i created another class called CalorieIntake where in here i'll calculate the total calorie intake. (i do this by extends the BMIcalculation class.)
Then when i click on the 'Check' button, it should compare between this two value and show the interpretation. However i keep getting error at the 'interpretDiff(float diffValue)' part it mentioned it must return with a String value.
Here are my codes..pls help me to check where to problem is. Or is there a better way to do so? pls advice me. Thanks a lot..
public class CalorieIntake extends BMIcalculation {
TextView counter1;
Button compare;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.form_calorieintake2);
Button btn_calcIntake = (Button) findViewById(R.id.button_calcIntake);
btn_calcIntake.setOnClickListener(btnListener_calcIntake);
counter1 = (TextView) findViewById(R.id.textView_totalCalorieIntake);
Button compare = (Button) this.findViewById(R.id.checkIntake);
compare.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try {
if ((!counter1.equals("")) && (!caloriesresult.equals("")))
{
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
}
}catch (Exception k)
{ System.out.println(k);
Toast.makeText(CalorieIntake.this, "Error", Toast.LENGTH_SHORT).show();
}
}
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
{
return "Eat more";
}
}
private float calDiff(float calorieIntake, float calorieNeed) {
return (float) (calorieIntake - calorieNeed);
}
});
}
In interpretDiff, what happens if diffValue is not less than 100? You return nothing. However, java requires that you return something, as that is what the declaration of the method implies.
A solution would be:
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
return "Eat more";
return "Eat less";
}
The else statement for if diffValue is not less than 100 is not necessary here because the second return statement is only called if diffValue >= 100 (since hitting a return statement exits out of the method).
With regards to the issue of the exception being thrown, and the Toast error being called, that can only happen as a result of the following code:
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
Assuming findViewById doesn't have an issue in it, the error is probably coming from getting the text of counter1E, caloriesresultE (if they are null). If neither of those are null, then check to make sure callDiff and interpretDiff don't have bugs in them. Finally, make sure compareText is not null.

Categories