Peele Peele - 1 year ago 83
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;

public void afterTextChanged(Editable s) {
if(flightNumber.getText().toString()!=null) {
int flightNo = Integer.parseInt(flightNumber.getText().toString());
if (flightNo >=30 && flightNo <=99) {
Toast.makeText(getApplicationContext(), getText(R.string.flight_warning), Toast.LENGTH_LONG)
} else {


This is the LOG

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

The crash is happening in this line:

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download