androidformsvalidationvalidatingvalidating-event

Android app shutting if form blank - Need a validation form


I have a app for convert km/h for mph. If the form is blank and press button convert, the app simply closes. I understand that i need a function thats validade if the form is blank and show a message informating users that form cannot be blank but i cannot found a code for my problem.

My onClick code is:

        buttonConverter.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            double Value1 = Double.valueOf(txtKmhUser.getText().toString());
            double Value2 = Value1 / 1.60;
            Result.setText(String.valueOf(Value2));

        }


    });

Solution

  • The reason your app is crashing is because Double.valueOf("") throws a number format exception. So you need to validate your form ahead of processing or use a try/catch for the exception.

    buttonConverter.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if(txtQuilometros.getText().toString().length() > 0) {
                 double Value1 = Double.valueOf(txtQuilometros.getText().toString());
                 double Value2 = Value1 / 1.60;
                 Result.setText(String.valueOf(Value2));
             } else {
              txtQuilometros.setError("Please enter a value");
        }
    });