0

I have a WebView(webView), ProgressBar(progress) and RelativeLayout(error). I need to show ProgressBar until the page loads and need to show WebView after the page successfully loads. If there's any error, it should show the RelativeLayout(error). The problem is that WebView is displayed if there's no network connectivity. How do I make it work ? Here's my code :

    webView.setWebViewClient(new WebViewClient(){

        @Override
        public void onLoadResource(WebView view, String url) {
            webView.setVisibility(View.GONE);
            progress.setVisibility(View.VISIBLE);
            error.setVisibility(View.GONE);
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            webView.setVisibility(View.VISIBLE);
            progress.setVisibility(View.GONE);
            error.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError errorWebResource) {
            webView.setVisibility(View.GONE);
            progress.setVisibility(View.GONE);
            error.setVisibility(View.VISIBLE);
            super.onReceivedError(view, request, errorWebResource);
        }

   });

    webView.loadUrl("https://www.google.com");
Hello World
  • 103
  • 1
  • 2
  • 6

1 Answers1

0
  1. in general terms, you want to have the super calls execute before your custom code, so you may want to start there. If you don't care about the super call, you may want to remove it instead.

  2. You may want to place a break point in onPageFinished. I suspect that's the call you get when there's no internet connection.

  3. Your issue may not be in the error section, but in the execution of your webView.loadUrl();

I would suggest you to review this accepted answer: Detect whether there is an Internet connection available on Android .There are also hundreds of other answers in SO on how to check for network connectivity in Android, if you don't like this answer.

So then your call would look something like this:

if (isNetworkAvailable) {
    webView.loadUrl("https://www.google.com");
} else {
    error.setVisibility(View.VISIBLE);
}

This way, if there's no network connection it won't even attempt to make the call.

Community
  • 1
  • 1
TooManyEduardos
  • 4,206
  • 7
  • 35
  • 66