In my app I have receive URLs as string from a web-service and load it to a WebView.
mainContentText = (WebView) findViewById(R.id.mainContentText);
mainContentText.getSettings().setJavaScriptEnabled(true);
mainContentText.setWebViewClient(new CustomWebClient());
mainContentText.loadUrl(url);
private class CustomWebClient extends WebViewClient{
private static final String TAG = "WebWiewActivity";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "loading: " + url);
return false;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.e(TAG, String.format("*ERROR* Code: %d Desc: %s URL: %s", errorCode, description, failingUrl));
}
}
When tested a situation when the URL is not good (a random string, url = "abc"
) I just receive a default error page, but nothing at onReceivedError
and not shouldOverrideUrlLoading
callbacks and no exceptions
How can I catch such situation?
I faced the same problem, i solved it like below:
private class CustomWebClient extends WebViewClient {
private static final String TAG = "WebWiewActivity";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "loading: " + url);
return false;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
*************************************
// do error handling
*************************************
}
@Override
public void onPageFinished(String url) {
// url validation
if (!Patterns.WEB_URL.matcher(url).matches()) {
*************************************
// do error handling
*************************************
}
}
}
I added some logic in onPageFinished(String url) method to check whether the url is valid, and you can catch the exception when the URL is not good (a random string, url = "abc").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With