我正在尝试将网页的一部分解析到WebView中。我使用jsoup库获取所需的页面部分,然后加载到webview中。 以下是代码:
public void loadArticleWithHTML (){
Thread downloadThread = new Thread() {
public void run() {
try {
doc = Jsoup.connect("http://en.wikipedia.org/").get();
element = doc.select("#mp-itn b a");
} catch (java.io.IOException e){
e.printStackTrace();
}
}
};
downloadThread.start();
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
}
});
try {
mWebView.loadData(element.html(), "text/html", "UTF-8");
} catch (NullPointerException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
但我总是遇到错误
尝试在空对象引用上调用虚拟方法“java.lang.String org.jsoup.select.Elements.html()”
A WebView method was called on thread 'Thread-159'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {b10dae3} called on null, FYI main Looper is Looper (main, tid 1) {b10dae3})
。我已经修改了代码 像这样。看起来现在它可以工作了。 - Personal Jesus