I need to cache a WebView in a way that it would use cache if there is no internet, and when there is internet it will use the online page. Since my class with the WebView does loadUrl() in the onCreateView, it reloads it every time so I need cache for 2 reasons: faster loading, but mainly for offline use of the app.
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.net.ConnectivityManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class CalendarFragment extends Fragment {
private WebView webView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.calendar_layout, container, false);
webView = (WebView) view.findViewById(R.id.calendarWebView);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCachePath(getContext().getCacheDir().getPath());
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://calendar.google.com/calendar/htmlembed?src=wlmacci%40gmail.com&ctz=America%2FToronto");
//webView.loadUrl("https://sites.google.com/view/wlmac/textfile?");
//webView.loadUrl("https://google.ca");
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
return view;
}
}
I have tried the LOAD_DEFAULT
as well as LOAD_CACHE_ELSE_NETWORK
and neither seem to work; when I switch away from Calendar fragment and back to it with my WiFi off, I get net::ERR_ADDRESS_UNREACHABLE
Update: Doesn't work with LOAD_CACHE_ONLY
either
Update: Added ACCESS_NETWORK_STATE
and ACCESS_WIFI_STATE
, am now getting net::ERR_INTERNET_DISCONNECTED
error