Error while subtracting with no value fields (Android)

Asked

Viewed 374 times

3

I got two camps like double, where the values should be subtracted. But when I do not enter any value in the field, an error occurs and the application closes. How can I solve this problem?

Follows the code:

final EditText primeiro = (EditText) findViewById(R.id.primeiro);
final EditText segundo = (EditText) findViewById(R.id.segundo);
Button botaoCalcular = (Button) findViewById(R.id.calcular);

botaoCalcular.setOnClickListener (new OnClickListener(){
    @Override
    public void onClick(View v) {           

        double num1 = Double.parseDouble(primeiro.getText().toString());
        double num2 = Double.parseDouble(segundo.getText().toString());     
        double res = num2 - num1;

        AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);
        dialogo.setTitle("Resultado");
        dialogo.setMessage("Resultado : " + res);
        dialogo.setNeutralButton("OK", null);
        dialogo.show();
    }
});
  • On which line does the error?

  • Probably the error occurs because you are trying to subtract the variable with NULL value, if this is the case you should check if it is null and put 0 in place.

  • It is not agreeing any error the way it is but if I do not put some value in the field at the time it is executing that the error happens and the application is closed, I wonder how I can solve it

  • If you have no data in the field, you will be converting null to double. Hence the error, probably nullpointerException. Validate the field by checking if it is not null before performing the operation.

  • Look at this reply a way to prevent this error from occurring without validation.

  • Which error occurs, is really the NullPointerException?

  • @ramaral even if the fields come with default value, nothing prevents a user from deleting and trying to do the empty operation, validation would not be a way to protect itself from that?

  • 2

    You are right @Diegofelipe, the fact of initializing the field and can only accept numbers does not prevent the user to make it null.

Show 3 more comments

2 answers

1

Try to validate the fields before performing any operation:

if(primeiro.getText() != null && segundo.getText() != null) {
    double num1 = Double.parseDouble(primeiro.getText().toString());
    double num2 = Double.parseDouble(segundo.getText().toString());

    double res = num2 - num1;
    AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);

    // setando título

    dialogo.setTitle("Resultado");

    // setando mensagem

    dialogo.setMessage("Resultado : " + res);
    // setando botão

    dialogo.setNeutralButton("OK", null);

    // chamando o AlertDialog
    dialogo.show();
}

You can also improve the code by displaying a message when trying to perform the operation with unfilled fields:

AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);
// setando título
dialogo.setTitle("Resultado");

if(primeiro.getText() != null && segundo.getText() != null){

    double num1 = Double.parseDouble(primeiro.getText().toString());  
    double num2 = Double.parseDouble(segundo.getText().toString());

    double res = num2 - num1;

    // setando mensagem
    dialogo.setMessage("Resultado : " + res);

    // setando botão
    dialogo.setNeutralButton("OK", null);

    // chamando o AlertDialog
    dialogo.show();
} else {
    // setando mensagem
    dialogo.setMessage("Os campos não podem ser vazios.");

    // setando botão
    dialogo.setNeutralButton("OK", null);

    // chamando o AlertDialog
    dialogo.show();
}

0


When developing functionalities in this way, we need to pay attention to the input of information, mainly ensuring whether it is valid or not.

In your case, I see two big points that could cause failure in your application:

1) - The user enter numeric alpha values, ie numbers and letters. If you try to do something similar to:

double num1 = Double.parseDouble("a");

You will receive Exception:

Caused by: java.lang.NumberFormatException: Invalid double: "a"

To prevent this, you need ensure that the user will only enter values valid in his EditText. For this, you can put the attribute inputText="number" directly in the xml of your component. This will make the keyboard style open for the user to enter the information of type number, that is, making it impossible for the user to enter letters:

<EditText
   android:id="@+id/seu_id"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="Insira um valor"
   android:inputType="number"/>

2) The user presses the button calcular forgetting to put valid information, for example, started typing and deleted all values and the EditText be empty. It would be like you trying to do this:

double num1 = Double.parseDouble("");

You will receive Exception:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference

To avoid this, you need to make a simple entry validation, to block the operation if invalid:

botaoCalcular.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {           
        String primeiroTexto = primeiro.getText().toString();
        String segundoTexto = segundo.getText().toString();

        if(validaInformacao(primeiroTexto, segundoTexto)){
            double num1 = Double.parseDouble(primeiroTexto);
            double num2 = Double.parseDouble(segundoTexto);     
            double res = num2 - num1;

            AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);
            dialogo.setTitle("Resultado");
            dialogo.setMessage("Resultado : " + res);
            dialogo.setNeutralButton("OK", null);
            dialogo.show();
        }
    }
});

private boolean validaInformacao(String primeiroTexto, String segundoTexto) {
    if (TextUtils.isEmpty(primeiroTexto)) {
        Toast.makeText(this, "O primeiro valor é inválido", Toast.LENGTH_SHORT).show();
        return false;
    } else if (TextUtils.isEmpty(segundoTexto)) {
        Toast.makeText(this, "O segundo valor é inválido", Toast.LENGTH_SHORT).show();
        return false;
    } else {
        return true;
    }
}

Browser other questions tagged

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