如何处理webview中的错误?

时间:2012-12-05 08:10:12

标签: android webview webviewclient

我想加载一个网页。

private class MyJavaScriptInterface {

    private MyJavaScriptInterface () {
    }

    public void setHtml(String contentHtml) {

        if (contentHtml != null && contentHtml.trim().length() > 0) {
            //Do something
        }
    }
}
private WebViewClient webViewClient = new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {

        view.loadUrl("javascript:window.ResponseChecker.setHtml"
            + "(document.body.innerHTML);");
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    public void onReceivedSslError(WebView view, SslErrorHandler handler,
        SslError error) {
        handler.proceed();
    }

    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Log.e("ProcessPayment", "onReceivedError = " + errorCode);
    }

};

我想处理网页加载错误。我知道错误可以通过onReceivedError(...)方法获得。

我的问题是如何在不在webview中显示Page Not found的情况下处理错误? (例如:显示一个对话框并将webview留空)。

先谢谢。

2 个答案:

答案 0 :(得分:7)

检查为:

 public void onReceivedError(WebView view, int errorCode, 
                           String description, String failingUrl) {
             Log.e("ProcessPayment", "onReceivedError = " + errorCode);

            //404 : error code for Page Not found
             if(errorCode==404){
               // show Alert here for Page Not found
               view.loadUrl("file:///android_asset/Page_Not_found.html");
             }
            else{

              }
           }

答案 1 :(得分:0)

public void onReceivedError(WebView view, int errorCode, String description,
        String failingUrl) {

    if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_FILE_NOT_FOUND) {
        // TODO your dialog here
    }
}