Android: Override the default WebView error page with your own.

1 Comment
I've finally had some time to update my Diablo II Runewords app a little, and was thinking of ways to hide my URL from the WebView error.
image
Surprisingly, it was very easy to do that. Just a quick look through the WebView/WebViewClient docs and you've quickly got your answer.
Set up your WebView with a new WebViewClient by calling:
1.webView.setWebViewClient(new NoErrorWebViewClient());

And here is the subclassed WebViewClient which handles errors:
01.class NoErrorWebViewClient extends WebViewClient {
02.  @Override
03.  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
04.    Log.e(String.valueOf(errorCode), description);
05. 
06.    // API level 5: WebViewClient.ERROR_HOST_LOOKUP
07.    if (errorCode == -2) {
08.      String summary = "<html><body style='background: black;'><p style='color: red;'>Unable to load information. Please check if your network connection is working properly or try again later.</p></body></html>";       view.loadData(summary, "text/html", null);
09.      return;
10.    }
11. 
12.    // Default behaviour
13.    super.onReceivedError(view, errorCode, description, failingUrl);
14.  }
15.}

And the result is...
image
Just a reminder that within the error handler you can also load a local resource/asset rather than building the HTML string.
bigtrouble5vt2eq1tw7ro5zz
Now, go back to doing more magic!

Update 24/01/2013: Moved super.onReceivedError() to the end of the call to prevent flickering.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog