How to treat exception in a Webview?

Asked

Viewed 796 times

13

I wanted to know how to treat exceptions in my Webview, because sometimes the site ta off, and the page does not load, and sometimes even crashes the application. I tried a try catch no load, but does not enter the exception, I want that when the server is off, it sends the message, SERVER UNAVAILABLE!

watch my webview:

public void carregarSite() {    

    // Verifica conexão
    if (verificaConexao()) { //se tiver conexao
        // Ajusta algumas configurações
        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setBuiltInZoomControls(true);
        wv.setWebViewClient(new WebViewClient());
        wv.setWebChromeClient(new WebChromeClient());

        try{
          wv.loadUrl(URL);
        } catch(Exception e){
            Toast.makeText(Main.this, "SERVIDOR INDISPONIVEL!", 1000).show();
        }
    } else           
        msgConexao(); // metodo de msg de conexao
}
  • 2

    He even implemented the method onReceivedError(WebView view, int errorCode, String description, String failingUrl) of WebChromeClient?

  • I believe it is enough for you to implement and do the treatment of errorCode which may vary according to the type of error. The list of possible errors is on this page: http://developer.android.com/reference/android/webkit/WebViewClient.html.

  • I implemented it this way: private class Mywebviewclient extends Webviewclient{ @Override public void onReceivedError(Webview view, int errorcode, String Description, String failingUrl) { Toast.makeText(Main.this, "Unavailable server", 1000). show(); super.onReceivedError(view, errorcode, Description, failingUrl); } however unsuccessfully

  • friend, I tried this solution : http://twigstechtips.blogspot.com.br/2013/android-override-default-webview-error.html, but nothing happens tbm, as I can go on?

  • 2

    Actually, HTTP errors are not notified by this callback, according to that Issue: https://code.google.com/p/android/issues/detail?id=32755. You will need to verify this by making an HTTP request to find out if the server responds with status 200...

1 answer

2

One way around this problem is by using a WebviewClient to handle error reception:

webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedError(final WebView view, int errorCode, String description,final String failingUrl) {
            Toast.makeText(Main.this, "SERVIDOR INDISPONIVEL!", 1000).show();
        }
});

The WebviewClient is linked to your object WebView and thus allows the implementation of the called method when some problem occurs in the loading of the object url WebView. Within it you can treat the exception amicably to the user, using the Toast, for example.

Source: https://stackoverflow.com/questions/18221728/handle-network-issues-in-webview.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.