-5

I'm building an app that uses json data from a server that changes everyday. Yesterday it worked perfectly. Today, however, i get the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference

at this line(s) of code:

if(!endDate.equals("") && !endDate.equals(null) && !endDate.equals("null")) {
      dates.append(" t/m ").append(endDate);
}

To me it seems that the if statement should avoid the nullpointer exception... Do i miss something?

Tom
  • 16,842
  • 17
  • 45
  • 54
jrip
  • 140
  • 1
  • 10

4 Answers4

0

The endDate variable is null and you can't call methods on that. These is the reason of the NullPointerException.

To avoid the exception, just verify if the variable is not null as the first check if the if statement:

if(endDate != null && !endDate.equals("")) {
      dates.append(" t/m ").append(endDate);
}
Lino
  • 5,084
  • 3
  • 21
  • 39
0

It means that your object endDate is null. You should check if you have initialised it somewhere prior to using it. Also add an if statement prior to your if statements,

if(endDate != null){
if(!endDate.equals("") && !endDate.equals("null")) {
      dates.append(" t/m ").append(endDate);
}
}
harshithdwivedi
  • 1,411
  • 16
  • 37
0

At a glance, looks like you need to null check the endDate variable itself like this. A method cannot be called on a null object, because basically the method does not exist without an instance.

if(endDate != null){
  if(!endDate.equals("") && !endDate.equals(null) && !endDate.equals("null")) {
      dates.append(" t/m ").append(endDate);
  }
}
Mark Giaconia
  • 3,844
  • 5
  • 20
  • 42
0

The NullPointerException means that your endDate variable is holding a reference to null. Using .equals() won't work with nul, because you'd be calling a method on a non-existent (null) object. You can check for it by using an assert statement (see https://en.m.wikibooks.org/wiki/Java_Programming/Keywords/assert) Like this: assert (endDate!=null);

Alternatively, you could just use if(endDate!=null);

However, if you actually want to fix things, you should wrap the block in a try statement and catch any NPE.

shalvah
  • 881
  • 10
  • 21