Ali Sheikhpour
Ali Sheikhpour

Reputation: 11045

WebView custom error page is not shown instantly

I use this code to redirect a user to a custom error page when the webView got errors however the browser error on the webpage is visible for a few milliseconds before redirecting to the custom error page.

The funny thing is that I have a try again button in error.html which tries to connect to the target webpage again. When I do fast clicks on try again, I can even see the browser error page clearly e.g. 404 page with the browser message web page is not available! This is not good because I want to completely hide the error especially the address of the webpage caused error which is visible in the browser error page.

public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    webview.post(new Runnable() {
    @Override
    public void run() {
        webview.loadUrl("file:///android_asset/htmls/error.html");
        }
    });
};

How should I hide the WebView instantly as soon as it receives an error? Is there another method to improve onReceivedError behavior?

Upvotes: 1

Views: 3406

Answers (2)

Jaspreet Kaur
Jaspreet Kaur

Reputation: 1720

Try This, this is the working code.

@Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(MainActivity.this, "Error! " + description, Toast.LENGTH_SHORT).show();
                //Clearing the WebView
                try {
                    view.stopLoading();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    view.clearView();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (view.canGoBack()) {
                    view.goBack();
                }
                String ErrorPagePath = "file:///android_asset/htmls/error.html";
                view.loadUrl(ErrorPagePath);

                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });

Upvotes: 3

Héctor M.
Héctor M.

Reputation: 2392

You are declaring WebView view, but you are referencing webview.post() and webview.loadUrl().

public void onReceivedError(WebView webview, int errorCode, String description, String failingUrl) {
    webview.post(new Runnable() {
    @Override
    public void run() {
        webview.loadUrl("file:///android_asset/htmls/error.html");
        }
    });
};

Upvotes: 0

Related Questions