1

I am trying to make a webview where the app loads a HTML page from assets if there is no internet connection. I have been following this QUESTION and i have made a CheckNetwork.java but where shall i put this code below into my MainActivity? I am a beginner at this so please explain as simple as possible.

if(CheckNetwork.isInternetAvailable(MainActivity.this)) 
  {
   // do something
  }

This is my MainActivity

public class MainActivity extends ActionBarActivity {

WebView browser;
private ourViewClient mClass;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mClass = new ourViewClient(this);

browser = (WebView) findViewById(R.id.wvwMain);

browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);

browser.setWebViewClient(new ourViewClient(this));
try {
    browser.loadUrl("http://MyWebPage");
}

catch (Exception e) {
    e.printStackTrace();
   }

  }

} 
Community
  • 1
  • 1
Ereck Taut
  • 65
  • 9

1 Answers1

0

This should do the trick for you:

if(CheckNetwork.isInternetAvailable(MainActivity.this)) 
   browser.loadUrl("http://MyWebPage");
} else {
   browser.loadUrl("file:///android_asset/your_html.html");
}

I am also including example of how you load a html from your assets.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • I made it work, thanks. I also had to include permission to `android.permission.ACCESS_NETWORK_STATE` in my manifest which i had not done. What was the function of the code `catch (Exception e) { e.printStackTrace();` ? – Ereck Taut Jun 04 '14 at 13:15
  • @EreckTaut: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html – Boris Strandjev Jun 04 '14 at 13:20
  • You can also load from R.raw. – Mgamerz Jun 04 '14 at 14:38
  • @Mgamerz difference being that the raw resources will not be compressed when shipped in the apk. As for the solution proposed - the OP explicitly asks about the assets solution. – Boris Strandjev Jun 04 '14 at 14:56