Matt Smeets
Matt Smeets

Reputation: 398

Android WebView, load from cache and attempt to refresh

I am trying to create a small app that loads a webpage and stores it in the cache. When swiping refresh it must attempt to update, but if there is no internet access it should keep the current version.

Currently, I've got "swipe to force refresh" and "load from the cache" working, but can not seem to figure out how to "attempt to refresh if possible".

swipeRefreshLayout = findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(
        new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                myWebView.clearCache(true);
                myWebView.reload();
            }
        }
);

WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setAppCachePath(getBaseContext().getCacheDir().getPath());
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

myWebView.loadUrl(config.getString("website_root"));
myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        if (!swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        swipeRefreshLayout.setRefreshing(false);
    }
});

Upvotes: 3

Views: 5593

Answers (1)

Sagar
Sagar

Reputation: 24917

Base on the documentation for WebSettings.LOAD_CACHE_ELSE_NETWORK:

Use cached resources when they are available, even if they have expired. Otherwise load resources from the network

Because of this you view is always loaded from cache.

You can use following method: 1. Check connectivity:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null;
}
  1. Before instead of setting:

    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setAppCachePath(getBaseContext().getCacheDir().getPath());
    
    webSettings.setCacheMode(isNetworkConnected()?WebSettings.LOAD_NO_CACHE: WebSettings.LOAD_CACHE_ONLY);
    
  2. On Swipe to refresh, you can do the same:

    swipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    if(isNetworkConnected()){
                        ...
                        myWebView.reload();
                    } else {
                          //Do something for non-connectivity
                    }
            }
        });
    

Upvotes: 3

Related Questions