user998441
user998441

Reputation:

Android webview onReceivedError display custom error page and reload previous url onResume

We suppose that a url is already loaded (Let's call it the original url).

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        webView.loadUrl("file:///android_asset/missing.html");
    } 
});

I have created my own error page to prevent the "web page not available message" to appear. The app must reload the webview every time it is resumed. So i have the following lines of code:

@Override
protected void onResume() {
    super.onResume();
    webView.reload();
}

The problem here is that when the error page is loaded (for example when the user is not connected to the internet), and then a connection is available again and the user resumes the app, the original url is not loaded (which seems logic, the current now is missing.html). But is this a nice approach? Any suggestions for the problem?

There is also a refresh button if the user wants to reload the content. Same issue here.

Upvotes: 7

Views: 8618

Answers (3)

MeatPopsicle
MeatPopsicle

Reputation: 992

It's not just the mobile connection that can drop but also the page can become unavailable and as you rightly say using webview.loadUrl("someerrorpage.html") will create fake history and cause problems if the user tries to refresh or press back.

My solution was to replace the contents of the default error page with my own custom one e.g.

webView.evaluateJavascript("javascript:document.open();document.write('your custom error html');document.close();", null);

Upvotes: 0

deviato
deviato

Reputation: 2056

You should load the wanted url instead of using webView.reload(), like this:

webView.loadUrl("http://yoururl");

or go back to previous page with:

webView.loadUrl("javascript:history.go(-1)");

Upvotes: 4

Jacob Nordfalk
Jacob Nordfalk

Reputation: 3533

I'd examine internet connectivity in onResume() like suggested on http://developer.android.com/training/basics/network-ops/managing.html

public static boolean isOnline() {
  ConnectivityManager connMgr = (ConnectivityManager) App.instans.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  return (networkInfo != null && networkInfo.isConnected());
}

public void onResume() {

Upvotes: 1

Related Questions