修复Async Try Catch(doInBackground()内部的NullpointException



我在运行下面的代码试图使用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;
}

更改

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

相关内容

  • 没有找到相关文章

最新更新