Android WebView onReceivedError()

According to documentation and my experience it should work quite fine. You just have to set your WebClient with overriden method onReceivedError in your WebView.

Here is the snippet from some of my old test app:

 WebView wv = (WebView) findViewById(R.id.webView);
 wv.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.i("WEB_VIEW_TEST", "error code:" + errorCode);
            super.onReceivedError(view, errorCode, description, failingUrl);
    }
 });

I've tested it and it works quite fine. Check your logs and see what kind of code error do you get. Hope it helps.


I have tried using onReceivedError both inside shouldOverrideUrlLoading() and outside that method but in the WebViewClient. I even tried outside in the main Activity class. I was not happy with the inconsistent results. So I settled on using a test method, isOnline(), and calling that before calling loadUrl().

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getBaseContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo i = cm.getActiveNetworkInfo();
    if ((i == null) || (!i.isConnected())) {
        Toast toast = Toast.makeText(getBaseContext(),
                "Error: No connection to Internet", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 0);
        toast.show();
        return false;
    }
    return true;
}

Then this onReceivedError is in the WebViewClient but outside the overloadurlthingy method. This seems to consistently prevent the stupid, smirking-android error pages.

    @Override
    public void onReceivedError(WebView view, int errorCode,
            String description, String failingUrl) {
        if (view.canGoBack()) {
            view.goBack();
        }
        Toast toast = Toast.makeText(getBaseContext(), description,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 0);
        toast.show();
    }

Some people might consider this resource-heavy. Well, not heavy the way the Android Facebook and Google+ apps are. And not the way Google services are. I frankly don't mind using up a little of those apps oxygen. Call me a bad boy...


You should use this after the on Page finished

 @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
           //Your code to do
        Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error , Toast.LENGTH_LONG).show();
    }