Reputation: 41
I want to load a webpage in webView online and offline both when there is no network it should load a last updated webpage.
I have tried this answer but this doesn't work for me. See the screenshot https://i.sstatic.net/PC4nC.png
Here is my source code:
public class tab1 extends Fragment {
WebView webView ;
ProgressBar progressBar;
protected File extStorageAppBasePath;
protected File extStorageAppCachePath;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.tab1,container,false);
webView = (WebView) view.findViewById(R.id.webview2);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar2);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://google.com");
return view;
}
public class myWebClient extends WebViewClient
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.GONE);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}
Upvotes: 0
Views: 3886
Reputation: 870
hey @Ayz Ali you are use Fragment
and getapplicationContext
is use in Activity
you can use getActivity
like this code
WebView webView = new WebView( context );
webView.getSettings().setAppCacheMaxSize();
webView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
if ( !isNetworkAvailable() ) { // loading offline
webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}
webView.loadUrl( "http://www.google.com" );
}
Upvotes: 3