Mdlc Mdlc - 1 month ago 11
Android Question

How can I show a custom "webpage not available" page in Android WebView?

I'm out to do something when no connection is available page/alert in

WebView
(e.g. load a local html page or alert). I've to play with Prevent WebView from displaying "web page not available" but without any success. Any suggestions would be appreciated.

Answer

It all came down to simply showing an AlertDialog from onReceivedError:

 @Override
 public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
                    //Clearing the WebView
                    try {
                        webView.stopLoading();
                    } catch (Exception e) {
                    }
                    try {
                        webView.clearView();
                    } catch (Exception e) {
                    }
                    if (webView.canGoBack()) {
                        webView.goBack();
                    }
                    webView.loadUrl("about:blank");

                    //Showing and creating an alet dialog
                    AlertDialog alertDialog = new AlertDialog.Builder(youractivity.this).create();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage("No internet connection was found!");
                    alertDialog.setButton("Again", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int which) {
                           finish();
                           startActivity(getIntent());
                       }
                    });

                    alertDialog.show();

                    //Don't forget to call supper!
                    super.onReceivedError(webView, errorCode, description, failingUrl);
                }

If you're new to WebView, you'll be looking to implement onReceivedError like this:

mWebView.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        //Code here
    }
});
Comments