Joe Winfield
Joe Winfield

Reputation: 829

How does one intercept the "Page Not Found" error in webview?

I am writing an app containing the WebView. and I want to put in some functionality to interecpt the "Page Not Found" message in case the content I am trying to show in my app ever is offline or for some other reason unreachable. I tried using the onReceivedError() but to no avail. Unless perhaps my syntax is wrong, but if soI don't see the error. can someone help?

code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("http://www.somesite.net");

    mWebView.setWebViewClient(new HelloWebViewClient()); 

    mWebView.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);
        //TO DO - do something else in here if the site is down
        }
      });


}
private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;

    }
}

Upvotes: 2

Views: 4588

Answers (2)

Paul
Paul

Reputation: 5924

Just came across this. onReceivedError() works fine. You will receive a -2 when the error happens.

Upvotes: 0

dongshengcn
dongshengcn

Reputation: 6504

The WebViewClient should be set before you load the url.

Upvotes: 1

Related Questions