0

I have this method in my superclass, which extends activity:

protected boolean isStopAvailable(BusStop stop) {
    if (stop == null) {
        stop = new BusStop();
    } else if (stop.getName().length() > 0) {
        return true;
    } else {
        return false;
    }
    return false;
}

I call it in my subclass isStopAvailable(object); How is it even possible to get a null pointer exception while using a method from the object after I've initiated the object?

1
  • If I may ask - which city? London? Commented Mar 14, 2012 at 9:22

5 Answers 5

3

stop.getName() returns null

else if (stop.getName() != null && stop.getName().length() > 0)

should solve it

Sign up to request clarification or add additional context in comments.

1 Comment

@user1163392, We've all been there :)
3

If getName() returns null, you will get a NPE. You are trying to do a length function on a null object, hence this exception. You should add another else if check:

...
else if (stop.getName() == null) {
    // do something
}

Hope this helps.

Comments

0

I would bet that the name field in stop is null. Your first check is to see if the object is null, not the fields inside of it. Thus, if stop.getName() returns null, you get an NPE when attempting to invoke the length

Comments

0

I suggest that the NPE is thrown in this line: else if (stop.getName().length() > 0)
Thats possible because you've checked if the object BusStop is null but you didn't checked if stop.getName() could be null.

Do something like that:

else if (stop.getName() == null) {
   // set stop.setName()
}

Hope this helped, Have Fun!

Comments

0

stop.getName() is returning null ,that is why you are getting NPE.

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.