Why does the application stop if the field is left empty?

0
public class VigMetBiapsb extends Activity {

int porctAlt, porctLarg;
double edtVaoNum;

EditText edtVao;
Button calcBiapsb;
TextView secaoBiapsb;

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

    edtVao = (EditText) findViewById(R.id.vao);

    calcBiapsb = (Button) findViewById(R.id.calc_biapsb);

    porctAlt = 6;
    porctLarg = 60;

    calcBiapsb.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            edtVaoNum = Double.parseDouble(edtVao.getText().toString());
            if(edtVao.getText().toString().equals("")){
                secaoBiapsb = (TextView) findViewById(R.id.valorsec);
                secaoBiapsb.setText("Dado inválido!");
            }
            else {
                double alt = edtVaoNum * porctAlt;
                double larg = alt / 100 * porctLarg;

                secaoBiapsb = (TextView) findViewById(R.id.valorsec);
                secaoBiapsb.setText(String.valueOf(alt)+" x "+String.valueOf(larg));
             }
        }
    });

    } //fecha onCreate
}

If I fill in the edtVao , everything runs correctly, but if I leave the edtVao empty, the application closes when I hit the calcBiapsb button.

Should not the edtVao.getText().toString().equals("") stretch within if avoid this? How can I check if the field is empty or not? (remembering that what is received from the field is passed to a variable double )

    
asked by anonymous 24.11.2014 / 20:45

1 answer

4

The error occurs before the check you are making.

Your application closes because when you click the button the application tries to extract a number of type double of the text contained in edtVao , which is empty. Pay attention to this line:

edtVaoNum = Double.parseDouble(edtVao.getText().toString());

The content of edtVao.getText().toString() is an empty string ( "" ), that is, it does not contain a valid double number. In this way, execution is equivalent to Double.parseDouble("") , which generates an exception of type NumberFormatException .

Attention should be paid to the log generated by the error (logcat), it is mentioned which exception occurred, a description of the error, and in which line of the code it occurred.

    
24.11.2014 / 21:02