Can anyone take a look at the below code and point out the obvious on what’s wrong? The program gives an error when editText is left blank and only does the calculation once all the information is present. Currently the program crashes when there is text missing, why is this?
EditText editText1, editText2;
double numA, numB, numC;
TextView answer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calc);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
}
public void btnClick(View v)
{
if(editText1.getText().length()==0)
{
editText1.setError("please input text");
}{
if (editText2.getText().length()==0)
{
editText2.setError("please input text");
}
numA = new Double(editText1.getText().toString());
numB = new Double(editText2.getText().toString());
numC=(numA + numB); answer.setText(Double.toString(numC));
}
}}
The problem is that you’re trying to parse
""into a number (a double, specifically). You are checking for empty values, but you’re still attempting to parse it even if you set the error. You need to place thenew Double()statements in a try-catch block, and catch the exceptions that happen when trying to parse an invalid input. This way, it’s safe even if the user inputs a random string of text that is also not parseable as a double.