Reputation: 9232
I want to remove the header
of a Webview
in an android App. I have found that it can be done programatically as:
Document document = Jsoup.connect(mUrl).get();
document.getElementsByClass("header").remove();
WebSettings ws = mWebView.getSettings();
ws.setJavaScriptEnabled(true);
mWebView.loadDataWithBaseURL(mUrl, document.toString(), "text/html", "utf-8", "");
The problem is that when the above code is executed, I receive a ThreadPolicyException
. I think the cause is that too much work on main Thread is executed. I knowe there is a solution, which is though considered to be "quick and dirty":
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
The recommended solution is that the code should be excecuted in a Background Thread (or in an AsyncTask
). When I try this however I receive also an Exception because of the call of methods on a Webview
on a Thread other than the UIThread
withe the message:
Calling View methods on another thread than the UI thread.;
java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
What is then the appropriate "clean" solution to this issue?
Upvotes: 1
Views: 1762
Reputation: 4857
Try insert your code inside runOniThread
:
getActivity().runOnUiThread( new Runnable() {
public void run() {
... your code
}
});
In my case this work fine inside background Threads (run from Fragment).
Add:
Also may be best way is javascript-injection:
public class MyWebViewClient extends WebViewClient {
@Override
public void onPageFinished( WebView view, String url) {
// ...
webview.loadUrl( "javascript: { document.getElementByClass('header').remove(); }");
// ...
}
}
webview.setWebViewClient( new MyWebViewClient());
Upvotes: 1