1

This is my code. As I am new to andorid, I have no idea what to do. This is what I have tried. Do I need to have some method to save cache to storage also?


public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        String url="https://www.facebook.com";

        WebView webView = (WebView) findViewById(R.id.webview_new);
        webView.setWebViewClient(new WebViewClient());

        if(!isNetworkAvailable()){
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        webView.loadUrl(url);
    }



    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Xantosh Lamsal
  • 349
  • 5
  • 14
  • Check Out This [Saving Webpage Using WebView](https://stackoverflow.com/questions/8410830/saving-webpage-in-cache-using-webview-in-android) – Hardik Bamaniya Jul 12 '17 at 09:22
  • this might help you,take a look https://stackoverflow.com/questions/35237197/cache-and-save-all-image-conten-in-webview-from-url-and-load-it/35252584#35252584 – seon Jul 12 '17 at 09:50

1 Answers1

1

You can add this cache() before isNetworkAvailable() so you can load the URL offline.

private void cache() {
        webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default
        if (!isNetworkAvailable()) { // loading offline
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
    }
Johny
  • 625
  • 2
  • 6
  • 26