0

I have the following code snippet.

Explanation: I have the array called result. This array consists of different String attributes like "city", "countryName" and "IATA".

With a for loop, I try to access and retrieve all the aforementioned fields.

My problem now is: While "city" and "countryName" always have a value, "IATA" sometimes does not have a value and thus returning me "null", which leads to the nullPointerException as soon as I access an empty "IATA".

I tried this:

if(entry.getIATA().equals(null)) {


                    } else {
                        startIATA[count] = entry.getIATA();
                    }

But, this if condition is not working as I try to access a field which is null. Has anyone an idea how I can solve this?

Here is the relevant code snippet:

private String[] startIATA = new String[200];  //That is more than long enough

...

for (int count = 0; count < result.getAirports().length(); count++) {
                    AirportsEntry entry = result.getAirports().get(count);

                    // Block for StartAirport

                    HorizontalPanel hp = new HorizontalPanel();
                    hp.setSpacing(5);
                    hp.add(new Label(entry.getCity()));
                    hp.add(new Label(entry.getCountryName()));
                    hp.add(new Label(entry.getIATA()));
                    GWT.log("IATA: " + entry.getIATA());

                    if(entry.getIATA().equals(null)) {


                    } else {
                        startIATA[count] = entry.getIATA();
                    }


                    startAirportVP.add(hp);

                }

Thank you very much for your time and your help!

2
  • I don't think you can do equal on null can you? Don't you need to do a "==" compare instead. Commented Feb 7, 2013 at 10:22
  • It is because ".equals" tries to call a method on a object (that's what "." means: call method). But, because your object is null, it errors because you can't call a method on something that doesn't exist. Instead, you can use " == " to check whether the object is null. Commented Feb 7, 2013 at 10:22

3 Answers 3

3

Perform a simple null check prior to accessing the property of the object.

if(entry != null && entry.getIATA() != null){
    startIATA[count] = entry.getIATA();
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you a lot for this superfast answer! It is working like it should :)
0

You cannot use equals method to check for null. Use ==:

if (entry.getIATA () == null)

Comments

0

use this: if (entry.getIATA() != null)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.