Error doing subtraction with fields with no value (Android)

3

I have two fields of type double , which should be subtracted between values. But when I do not enter any value in the field, an error occurs and the application closes. How can I solve this problem?

Follow 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();
    }
});
    
asked by anonymous 06.01.2016 / 20:20

2 answers

0

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

In your case, I see two major points that can cause your application to fail:

1) - The user enters numerical alpha values, that is, numbers and letters. If you try to do something like:

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

You will receive the exception:

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

To avoid this, you need to ensure that the user will only enter valid values in their EditText . For this, you can put the inputText="number" attribute directly in the xml of your component. This will make the keyboard style open for the user to enter the information to be 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 calcular button forgetting to enter valid information, for example, started typing and erased all values and EditText is empty. It would be like you trying to do this:

double num1 = Double.parseDouble("");

You will receive the 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 do a simple input validation , to block the operation if it is 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;
    }
}
    
07.01.2016 / 13:49
1

Try to validate the fields before doing 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 attempting 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();
}
    
06.01.2016 / 20:44