在异步尝试捕获(doInBackground()中修复NullpointException

时间:2018-07-11 04:57:38

标签: android android-asynctask jsoup

运行以下代码尝试使用JSoup解析网站时出现此错误。

错误

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

网站没有具有指定ID(getElementById('ctl00_ContentPlaceHolder1')的表。如何解决不存在表的异常?

代码

@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;
}

1 个答案:

答案 0 :(得分:0)

更改

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

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.
}