Lulzim Fazlija
Lulzim Fazlija

Reputation: 885

Android: Need help, trying to parse a HTML page using JSoup parser

Here is the code so far I am trying but it is showing me error:

URL url = null;
try {
    url = new URL("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)");
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("1");
Document doc = null;
try {
    System.out.println("2");
    doc = Jsoup.parse(url, 3000);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("3");
Element table = doc.select("table[title=Avgångar:]").first();
System.out.println("4");
Iterator<Element> it = table.select("td").iterator();

//we know the third td element is where we wanna start so we call .next twice
it.next();
it.next();
while(it.hasNext()){
  // do what ever you want with the td element here
System.out.println(it.next());
  //iterate three times to get to the next td you want. checking after the first
  // one to make sure
  // we're not at the end of the table.
  it.next();
  if(!it.hasNext()){ 
    break;
  }
  it.next();
  it.next();
}

It prints System.out.println("3");

then it stops in this line

Element table = doc.select("table[title=Avgångar:]").first();

How can i solve this problem,

Thanks

Upvotes: 0

Views: 334

Answers (2)

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

It looks like the website you're trying to parse the HTML from has an error and doesn't have any tables on it. This is what's causing the null pointer exception. doc.select("table[title=Avgångar:]") isn't returning an element and then you're trying to call a method on it. To prevent this error from happening again, you could do something like this:

Elements foundTables = doc.select("table[title=Avgångar:]");
Element table = null;
if(!foundTables.isEmpty()){
  table = tables.first();
}

Now, if any table was found, the table variable won't be null. You'll just have to alter the code to adapt in case no tables are found.

Upvotes: 1

Jason LeBrun
Jason LeBrun

Reputation: 13293

You're not checking the result of doc.select() before calling .first(). If there are no elements in the document that match the specified query, doc.select() could return null. Then you are calling .first() on a null pointer which, of course, will throw an exception. There is no table tag with the title you have specified in the document that you are using in your example. So, the result is not surprising.

Upvotes: 0

Related Questions