Reputation: 5737
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?
Upvotes: 6
Views: 2093
Reputation: 965
If the WebView can't handle the url it seems to return "about:blank" in the onPageStarted callback. Not sure if this is better or worse than Xiaozou's answer.
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.equals("about:blank"))
// handle no connection
}
Upvotes: 0
Reputation: 1665
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").
Upvotes: 3