I have an Android app that simply houses a website. I would like the app to cache the pages of the website for offline use.
I\'m doing a simple test to see if the cache
There are occasions that a WebView cannot be cached natively. If the page header contains the following fields, the WebView will not be able to cache the contents from that page.
Cache-Control: no-store, no-cache
Pragma: no-cache
In this case, youwill have to modify the page property on the server to solve the caching problem.
Its little Silly that this works. There is a redirect in URL from
http://www.bmimobile.co.uk/
to
http://www.bmimobile.co.uk/index.php
You Should try
webView.loadUrl("http://www.bmimobile.co.uk/why-bmi.php", getHeaders()); webView.loadUrl("http://www.bmimobile.co.uk/index.php", getHeaders());
This is not the exact answer to your question, as you are asking about webview cache. But, it can achieve the same result.
// saving page from web to file
File file = new File(this.getExternalFilesDir(null), "fileName.html");
FileUtils.copyURLToFile(new URL("http://www.bmimobile.co.uk/why-bmi.php"), file);
// loading saved file in webview
webview.loadUrl("file://" + file.getPath());
This is a more flexible approach, as you have control over loading, saving, and much more.
Perhaps a solution to your problem would be to make an HTTP get request alongside your webview loading.
The result of the get request could be stored in a string persistenly in sharedpreferences, and it will be the HTML that your php renders.
in your android lifecycle, you can determine if the app is offline, and if it is offline you can load the last saved version of the site from string
webview.loadData(yourSavedString, "text/html", "UTF-8");
although if there are images you will have to make extra considerations, but if the images are not dynamic you can store them in your app's asset folder and replace the URL in the saved string with the asset locations.
although it does not solve why your webview is not caching, it will accomplish the same end goal or viewing the page offline
Another very flexible and powerful option can be using HTML5 to manage the caching in your app..
Have a look at http://diveintohtml5.info/offline.html
You can simply enable caching in your app and manage the caching from the web end itself.
Best Regards
Aman Gautam