Question:
I have two fields of type double
, where a subtraction must be done between the values. But when I don't enter any value in the field, an error occurs and the application closes. How can I solve this problem?
Here's 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();
}
});
Answer:
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 they try 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();
}