I use webview to load html pages and urls.
I want to load url only if internet is available or if the url content is cached by the web view.
How can I check if a url is cached without having to create my own cache on some external path.
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wv.setOnTouchListener(this);
wv.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!url.contains("http")) {
view.loadUrl(url);
} else {
if (Utils.isConnectingToInternet(thisActivity)) {
view.loadUrl(url);
}
}
view.loadUrl(url);
return false;
}
I have referred to :
WebView Cache Data Directory?
Check if file already exists in webview cache android
How to move webView cache to SD?
Android webview check if page is in cache
Set webview cache mode LOAD_CACHE_ELSE_NETWORK.
Override WebViewClient methods :
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.getUrl().equals(failingUrl)){
showInternetConnectionError();
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
It will load webpage from server if internet connection available, otherwise load from cache. If webpage is not available in cache then it will display internet connection error.
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