0

Using webview the following code will execute fine on online and it will display the PDF file. After that if i goes to offline it will not display the cached pdf file.

mWebview.getSettings().setJavaScriptEnabled(true);
String pdfStr="https://www.sample.structure.first.pdf";
mWebview.loadUrl("https://docs.google.com/gview?embedded=true&url=" + pdfStr);

But i need to cache the pdf and display it on offline mode also. Anybody have any idea about this?

krish
  • 213
  • 1
  • 10

1 Answers1

1

You can save your work in cache of Web view using following:

WebView webView = new WebView( context );
webView.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 );
webView.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );

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

webView.loadUrl( "your_url" );

Add this method to check if network is available:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Add these permissions in your manifest :

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Pinks
  • 958
  • 7
  • 10
  • Still it is not working. It shows "Couldn't find the URL Click refresh to reload the page." – krish Apr 26 '16 at 09:17