使用空edittext单击按钮后应用程序崩溃

时间:2014-07-21 15:05:58

标签: android crash android-edittext

我正在研究BMI计算器应用程序。它有两个editText,一个按钮和三个textView。如果单击该按钮,则会获得BMI,但当一个或两个edittext字段为空时,应用程序崩溃。我在代码中看不到任何错误。你能救我一个人吗? 非常感谢

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calculator);
}

public void calculateClickHandler(View view) {

    if (view.getId() == R.id.calculateButton) {

        EditText weightText = (EditText)findViewById(R.id.weightText);
        EditText heightText = (EditText)findViewById(R.id.heightText);
        TextView resultText = (TextView)findViewById(R.id.resultLabel);

        float weight;
        if ("".equals(weightText.getText())) {
            weight = 1;
        } else {
            weight = Float.parseFloat(weightText.getText().toString());
        }

        float height;
        if ("".equals(heightText.getText())) {
            height = 1;
        } else {
            height = Float.parseFloat(heightText.getText().toString());
        }

        float bmiValue = calculateBMI(weight, height);
        String bmiInterpretation = interpretBMI(bmiValue);
        resultText.setText(bmiValue + "-" + bmiInterpretation);
    }
}

private float calculateBMI (float weight, float height) {
    return (float) (weight / ((height / 100) * (height / 100)));
}

private String interpretBMI(float bmiValue) {
    if (bmiValue < 16) {
        return "Severely underweight";
    } else if (bmiValue >=16 && bmiValue < 18.5) {
        return "Underweight";
    } else if (bmiValue >= 18.5 && bmiValue < 25) {
        return "Normal";
    } else if (bmiValue >= 25 && bmiValue < 30) {
        return "Overweight";
    } else if (bmiValue >= 30) {
        return "Obese";
    } else {
        return "Incorrect BMI";
    }
}

4 个答案:

答案 0 :(得分:0)

试试这个:heightText.getText().toString()

答案 1 :(得分:0)

您的应用崩溃的原因是这些if声明:

if ("".equals(weightText.getText())) {
    weight = 1;
}

weightText.getText()不会返回String,而是Editable。此外,Strings有一个名为isEmpty()的方法来检查它们是否为空。所以用这样的东西替换你的ifs:

if(weightText.getText().toString().isEmpty()) {
    ...
}

我希望我能帮到你,如果你有任何其他问题,请随时提出来!

答案 2 :(得分:0)

使用&#34;&#34;初始化您的EditText。 例如:

<EditText
    android:id="@+id/weightText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
 />

并更改

weightText.getText()

weightText.getText().toString();

答案 3 :(得分:0)

根据我在帖子中的内容,您可以尝试:

float weight;
if (weightText.getText() == null || "".equals(weightText.getText().toString())) {
    weight = 1;
} else {
    weight = Float.parseFloat(weightText.getText().toString());
}

float height;
if (heightText.getText() == null || "".equals(heightText.getText().toString())) {
    height = 1;
} else {
    height = Float.parseFloat(heightText.getText().toString());
}

希望这有帮助。