0

I have a class file which when i compile shows me Null pointer exception in a particular line all the time. I handled null check as below.

108    doc = Jsoup.parse(html, brandUrl);

109    Element div = doc.getElementById("eventTTL");
110    String attr = div.attr("eventTTL");
111    Date closingDate = new Date(Long.parseLong(attr));
112    Elements mainForm = doc.select("div#main-form");
113    Elements mainDivs = mainForm.select("DIV");

java.lang.NullPointerException at com.textT.at.Chickyur.main(Chickyur.java:110)

if(div != null)
String attr = div.attr("eventTTL"); 

 Also tried 
 if(div.attr("eventTTL") != null)
 String attr = div.attr("eventTTL"); 

Still i keep getting the exceptions. What is wrong? any thoughts?

Geek
  • 3,187
  • 15
  • 70
  • 115

3 Answers3

2

I can't tell by the code posted above exactly how your code is structured, but this should fix the NullPointerException:

Element div = doc.getElementById("eventTTL");
String attr = "";

if(div != null)
    attr = div.attr("eventTTL");

If you continue getting Exceptions after that, I would guess the issue is elsewhere in the code and you need to update your example.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

The code change you made will result in a compile error. No class file will be created, so you are probably running the old broken class file.

You probably want do do this (extend the scope of the if).

doc = Jsoup.parse(html, brandUrl);

Element div = doc.getElementById("eventTTL");
if(div != null) {
    String attr = div.attr("eventTTL");
    Date closingDate = new Date(Long.parseLong(attr));
    Elements mainForm = doc.select("div#main-form");
    Elements mainDivs = mainForm.select("DIV");
    ...
}
ILMTitan
  • 10,751
  • 3
  • 30
  • 46
0

Without seeing your stack trace, I'm only guessing, but:

From the line you say is the error, it means that div is null, which would indicate that the previous line is the culprit, which would mean that your doc has no Element with an Id of eventTTL.

Try ensuring that your doc is valid, and the it actually has a eventTTL.

Nicholas
  • 7,403
  • 10
  • 48
  • 76