Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android webview catch bad url

In my app I have receive URLs as string from a web-service and load it to a WebView.

mainContentText = (WebView) findViewById(R.id.mainContentText); 
mainContentText.getSettings().setJavaScriptEnabled(true);
mainContentText.setWebViewClient(new CustomWebClient());

mainContentText.loadUrl(url);

private class CustomWebClient extends WebViewClient{

        private static final String TAG = "WebWiewActivity";

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "loading: " + url);
            return false;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e(TAG, String.format("*ERROR*  Code: %d  Desc: %s  URL: %s", errorCode, description, failingUrl));
        }
    }

When tested a situation when the URL is not good (a random string, url = "abc") I just receive a default error page, but nothing at onReceivedError and not shouldOverrideUrlLoading callbacks and no exceptions
How can I catch such situation?

like image 690
NickF Avatar asked Mar 09 '14 13:03

NickF


1 Answers

I faced the same problem, i solved it like below:

private class CustomWebClient extends WebViewClient {

    private static final String TAG = "WebWiewActivity";

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Log.d(TAG, "loading: " + url);
        return false;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);

        *************************************
        // do error handling
        *************************************
    }

    @Override
    public void onPageFinished(String url) {
        // url validation
        if (!Patterns.WEB_URL.matcher(url).matches()) {
            *************************************
            // do error handling
            *************************************
        }
    }
}

I added some logic in onPageFinished(String url) method to check whether the url is valid, and you can catch the exception when the URL is not good (a random string, url = "abc").

like image 136
Xiaozou Avatar answered Nov 11 '22 05:11

Xiaozou