1

My Android Studio App has to show an offline site if there's no internet connection. And show an online website if internet connection is active.

Now I look up for the function if a Internet connection is active the online site is showing now. If i deactivate now the Internet connection it has to show the offline site again and not the standard "Error Site is not avaiable" - Error Page. How to fix this?

WebView wb;

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

    wb = (WebView) findViewById(R.id.mywb);
    wb.setWebViewClient(new MyBrowser());

    if ( !isNetworkAvailable() ) { // loading offline
        wb.loadUrl("file:///android_asset/index.html");

    }else { // loading online
        wb.loadUrl("http://www.google.com");
    }


}

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

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
J. Dake
  • 13
  • 2

1 Answers1

0

You almost have it: Just add the distinction in the WebViewClient when loading a new website.

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      if ( !isNetworkAvailable() ) { // loading offline
          view.loadUrl("file:///android_asset/index.html");
      }
      else { // loading online
          view.loadUrl(url);
      }
      return true;
     }
  }
Robert
  • 353
  • 3
  • 12
  • Unfortunately dosn't work if i klick on a Submit Button in the WebView. It shows the standard Error Page – J. Dake Nov 04 '17 at 22:23
  • Looks like the App has some Trouble generally with
    whitch used in webviews... Everytime when i click on a button in a Form-Field it shows the standard Error Page ..
    – J. Dake Nov 04 '17 at 23:01
  • did you enable javascript? if the form opens another website, it will pass through the webview client – Robert Nov 04 '17 at 23:46
  • Yes, javascript is enabled is it a problem? The form dosn't open another website it just start another data from the same serveradress... – J. Dake Nov 05 '17 at 05:51
  • Well, after a while testing I can say the Problem only exist if the
    method is "post". If the
    method is "get" it have no Problems. But i have to use the "Post" function for the forms. Is there any way to fix the Problem?
    – J. Dake Nov 05 '17 at 18:33
  • https://stackoverflow.com/questions/3664440/android-how-to-intercept-a-form-post-in-android-webviewclient-on-api-level-4 – Robert Nov 07 '17 at 09:39