Android ProgessBar while loading WebView

Swayam picture Swayam · Jun 28, 2012 · Viewed 72.8k times · Source

In my application, I have a WebView which loads any URL from the internet. Now, sometimes due to slow networks the page takes a long time to load and the user sees only a blank screen.

I want to show a ProgressBar while the WebView gets loaded and hide the ProgessBar when the WebView gets loaded completely.

I know how to use the ProgressBar and AsyncTasks, but here is my problem.

This is the code that I use to load my WebView.

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebViewClient(new HelloWebViewClient());
    mWebView.loadUrl(web_URL);

And this my custom WebViewClient class

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Now, if I try to show the ProgressBar using AsyncTasks then I guess I would have to give the code to load the URL in the doInBackGround() function of my AsyncTask and show the progress through the onProgressUpdate() function.

But, how do I load the URL inside the doInBackground() as doInBackground() runs on the Non-UI thread and I wont be able to use mWebView.loadUrl(web_URL) inside it.

Any suggestions? Am I missing something obvious? Please guide me.

Answer

Md Abdul Gafur picture Md Abdul Gafur · Jun 28, 2012

Check the source code. Help you and solve your problem...

public class AppWebViewClients extends WebViewClient {
     private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

I think it help you.

Thanks.