简体   繁体   中英

load url in webview with asynch task fails

I am trying to load my webview on another thread so that after the request loads I can add a button to the screen.

I do that like this:

private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                MyView myView = new myView();
                myView.setUrl(url);
                myView.setWebView(view);

                new DownloadFilesTask().execute(myView);
            return true;
        }
    }


private class DownloadFilesTask extends AsyncTask<MyView, Integer, Long> {
        protected Long doInBackground(MyView... myView) {

            long totalSize = 0;
            MyView amyView = myView[0];

           WebView view = amyView.getWebView();
           String url = amyView.getUrl();
            view.loadUrl(url);

            return totalSize;
        }

        protected void onProgressUpdate(Integer... progress) {

        }

        protected void onPostExecute(Long result) {
            rl.setVisibility(View.VISIBLE);
        }
    }

I get the error:

  Caused by: java.lang.RuntimeException: java.lang.Throwable: Warning: A WebView method was called on thread 'AsyncTask #2'. All 

WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.

How do I make the view visible after the url loads?

You should not be loading a WebView in a background thread; it needs to be loaded on the UI thread.

I would add a listener to your WebView and when the URL is finished loading you can add your button.

yourWebView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // add your button here
    } 
}); 

yourWebView.loadUrl(url);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM