Why does the app stop when I leave the field empty?

Asked

Viewed 360 times

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 the edtVao, everything is executed correctly, but if I leave the edtVao empty, the application closes when I touch the button calcBiapsb.

The excerpt edtVao.getText().toString().equals("") within the if shouldn’t avoid this? How could I check whether the field is empty or not? (remembering that what is received from the field is passed to a variable double)

1 answer

4


The error occurs before the check you are doing.

Your application closes because by clicking the button the application tries to extract a type number double of the text contained in edtVao, that is empty. Pay attention on this line:

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

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

Pay attention to the log generated by the error (logcat), it mentions which exception occurred, a description of the error, and on which line of code it occurred.

  • Fixed moving this line inside the else. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.