当没有输入数据时程序崩溃,数据很好(android)

时间:2012-12-02 17:07:34

标签: android android-edittext

我遇到的问题是,当我完全没有输入数据或者其中一个输入框中只有数据时,程序崩溃了,但如果两个框中都有数据,程序运行正常,那么我该怎么办如果没有输入则停止发送数据。错误说它可以解析值“”

的两倍
    calculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            distanceTraveled = Double.parseDouble(distance.getText().toString());
            fuelUsed = Double.parseDouble(fuel.getText().toString());
            part1 = fuelUsed / 4.55;
            mpg = distanceTraveled / part1;
            total.setText(String.format("%.2f", mpg));
        }
    });

2 个答案:

答案 0 :(得分:1)

在进行计算之前,将编辑视图更改为空或null:

alculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          if(distance.getText().toString().length() > 0){

            distanceTraveled = Double.parseDouble(distance.getText().toString());
        }
        else{
              distanceTraveled=0; // put default value here
          }
        if(fuel.getText().toString().length() > 0){  
               fuelUsed = Double.parseDouble(fuel.getText().toString());
          }
          else{
               fuelUsed=0;// put default value here

           }
            part1 = fuelUsed / 4.55;
            mpg = distanceTraveled / part1;
            total.setText(String.format("%.2f", mpg));
        }
    });

答案 1 :(得分:0)

在尝试从输入字段中检索值之前,请检查它们是否为空:

if (distance.getText() != null && fuel.getText() != null ) {
    distanceTraveled = Double.parseDouble(distance.getText().toString());
    fuelUsed = Double.parseDouble(fuel.getText().toString());
    part1 = fuelUsed / 4.55;
    mpg = distanceTraveled / part1;
    total.setText(String.format("%.2f", mpg));
} else {
    // You can display a message here for example Toast message that fields cannnot be empty
{