Android webview catch bad url

In my application, I get the URLs as a string from a web service and load it into 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 checking a situation where the url is not good (random string, url = "abc" ), I just get the default error page, but nothing in onReceivedError , and callbacks and no exceptions should shouldOverrideUrlLoading
How can I catch such a situation?

+6
source share
1 answer

I ran into the same problem, I solved it as shown 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 to the onPageFinished (String url) method to check if the url is correct and you can catch an exception when the url is not good (random string, url = "abc").

+2
source

All Articles