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;
}
}