WebViewClient onReceivedError deprecated, new version does not detect all errors

AndroidWebview

Android Problem Overview


In the Android SDK 23 onReceivedError(WebView view, int errorCode, String description, String failingUrl) has been deprecated and replaced with onReceivedError(WebView view, WebResourceRequest request, WebResourceError error). However if I put my phone in Airplane mode and load an url on my WebView, only the deprecated version of the method is called.

onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse) is also not useful, as it only detects errors higher than 500, and I am getting a 109 status code.

Is there a non-deprecated way of detecting that my WebView failed to load?

Android Solutions


Solution 1 - Android

You could also do following:

@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    // Handle the error
}

@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    // Redirect to deprecated method, so you can use it in all SDK versions
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}

Make sure you import android.annotation.TargetApi

Solution 2 - Android

Please note that the mobile device where you are testing needs to actually run Android Marshmallow (API 23). Even if you develop your app on API 23 SDK, but then run the app on Android Lollipop, you will still be getting the "old" onReceivedError, because it's the feature of the OS, not of an SDK.

Also, the "error code 109" (I guess, this is net::ERR_ADDRESS_UNREACHABLE) is not an HTTP error code, it's Chrome's error code. onReceivedHttpError is only called for the errors received from the server via HTTP. When the device is in airplane mode, it can't possibly receive a reply from a server.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin EpszView Question on Stackoverflow
Solution 1 - Androidxdevs23View Answer on Stackoverflow
Solution 2 - AndroidMikhail NaganovView Answer on Stackoverflow