How to handle exception in a Webview?

13

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

See 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
}
    
asked by anonymous 24.10.2014 / 22:15

1 answer

2

One way to work around this problem is to use 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 WebView object and thus allows the implementation of the called method when there is a problem loading the url of the WebView object. Within it you can treat the exception amicably for the user, using Toast , for example.

Source: link .

    
10.09.2016 / 00:23