简体   繁体   中英

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)

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;

}

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM