Peele Peele - 3 months ago 8
Java Question

Comparing a text to integer, Number format exception

I have a text field where the user can enter any number and when the user enters a number between 100 and 200, the button should get disabled. I have converted the text field to integer and comparing the text entered to a number. But I'm getting a crash.

private EditText flightNumber;

@Override
public void afterTextChanged(Editable s) {
if(flightNumber.getText().toString()!=null) {
int flightNo = Integer.parseInt(flightNumber.getText().toString());
if (flightNo >=30 && flightNo <=99) {
saveButton.setEnabled(false);
saveButton.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), getText(R.string.flight_warning), Toast.LENGTH_LONG)
.show();
} else {
saveButton.setEnabled(true);
saveButton.setVisibility(View.VISIBLE);
}
}
verifyFlightKeyData();
checkMandatoryFields();

}


This is the LOG

java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:137)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:331)
at com.miairline.chooseflight.FlightDataActivity$1.afterTextChanged(FlightDataActivity.java:112)
at android.widget.TextView.sendAfterTextChanged(TextView.java:8939)


The crash is happening in this line:

int flightNo = Integer.parseInt(flightNumber.getText().toString());

Answer

What's happening is that your text field is empty and you are trying to convert an empty string "" to a number.

Rather than:

if (flightNumber.getText().toString()!=null)

which will always be true, because toString() never returns null, you can do this:

if (flightNumber.getText().length() > 0)

which checks that the field is not empty.