-1

I am having this error when running the below code trying to parse the website using JSoup.

ERROR

java.lang.RuntimeException: An error occurred while executing doInBackground()
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.jsoup.select.Elements org.jsoup.nodes.Element.getElementsByTag(java.lang.String)' on a null object reference

The website doesn't have table with the specified id (getElementById('ctl00_ContentPlaceHolder1'). How to fix this exception where the table isn't present?

CODE

@Override
protected Void doInBackground(Void... voids) {
    try {
        Document evalPage = Jsoup.connect("http://site.example.com")
                .cookies(loginCookies)
                .timeout(30 * 1000)
                .execute().parse();

       //TODO FIX THE NO TABLE REFERENCE

        table = llPage.getElementById("ctl00_ContentPlaceHolder1").getElementsByTag("table").get(2);

    } catch (IOException ex) {
        ex.printStackTrace();
        parsingSuccessful = false;
    }
    return null;
}
Sreekant Shenoy
  • 1,420
  • 14
  • 23

1 Answers1

0

Change

table = llPage.getElementById("ctl00_ContentPlaceHolder1").getElementsByTag("table").get(2);

to

Element ele= llPage.getElementById("ctl00_ContentPlaceHolder1");
if (ele!= null){
   table = ele.getElementsByTag("table").get(2); // Check for the index as well, can throw exception otherwise.
}
gvmani
  • 1,580
  • 1
  • 12
  • 20
  • I had tried this before, but that doesn't solve it. The problem is, what if the first condition itself is wrong? `Element ele= llPage.getElementById("ctl00_ContentPlaceHolder1");` – Sreekant Shenoy Jul 11 '18 at 05:12
  • @SreekantShenoy the point is you need to make sure that you are not invoking funcitons on a null object. Depending on your code, you will have to make multiple checks to do it or try using Optional – gvmani Jul 11 '18 at 05:18
  • Hmm.. The problem is that the website shows the table only at some point of time.. Lemme see. Thank you though :) – Sreekant Shenoy Jul 11 '18 at 05:20