当EditText为空时,Android应用程序崩溃

时间:2014-07-03 16:25:08

标签: android android-edittext

这是一个简单的小费计算器,每当我的一个EditText框为空并按下按钮时,它就会崩溃。我的印象是应该有一个try / catch或if语句来处理异常,但我似乎无法让它工作。我正在把我的头发拉出来,因为我认为这是一个快速修复,所以任何帮助都会非常感激。

package com.gamejig.tip_calculator.tip_calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

    public class MainActivity extends Activity {
        double tipAmount;
        double finalBill;
        double billBeforeTip;
        double tipPercentage;

        TextView txt_Tip_Amount1;
        TextView txt_Final_Bill;
        EditText txt_BillBeforeTip;
        EditText txt_Tip_Percentage;

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

        txt_Tip_Amount1 = (TextView) findViewById(R.id.txt_Tip_Amount);
        txt_Final_Bill = (TextView) findViewById(R.id.txt_Final_Bill);
        txt_BillBeforeTip = (EditText) findViewById(R.id.txt_Bill_Amount);
        txt_Tip_Percentage = (EditText) findViewById(R.id.txt_Tip_Percentage);

        setupMessageButton();
    }

    public void setupMessageButton() {
        Button button= (Button) findViewById(R.id.btnCalculate);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                billBeforeTip = Double.parseDouble(txt_BillBeforeTip.getText().toString());
                tipPercentage = Double.parseDouble(txt_Tip_Percentage.getText().toString());

                tipAmount = billBeforeTip * tipPercentage;
                finalBill = tipAmount + billBeforeTip;
                txt_Tip_Amount1.setText(String.format("%.02f", tipAmount));
                txt_Final_Bill.setText(String.format("%.02f", finalBill));

            }
        });
    }

}

1 个答案:

答案 0 :(得分:0)

 billBeforeTip = Double.parseDouble(txt_BillBeforeTip.getText().toString());
 tipPercentage = Double.parseDouble(txt_Tip_Percentage.getText().toString());

更改为

 try {
     billBeforeTip = Double.parseDouble(txt_BillBeforeTip.getText().toString());
     tipPercentage = Double.parseDouble(txt_Tip_Percentage.getText().toString());
 } catch ( Exception e) {
     Log.e("InvalidNumber","Can not parse zero string"); 
     return; // Or another exception handling.
 }  

你有一个解析错误。因为您无法将""转换为Double