Search code examples
androidandroid-activitywebviewandroid-webviewcustom-error-pages

How to add a Custom Error page in an Android WebView application without any errors?


The following code is the MainActivity of the app. I tried to add a Custom Error page by using:

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

When I use the above code in the main activity either the Error page or the Loading Icon are working at a time. (overriding each other).

I'm not understanding where I'm mistaking. Can anyone please help me fix this problem? Thanks in advance.

public class MainActivity extends AppCompatActivity {

public WebView mywebView;

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

    mywebView = (WebView)findViewById(R.id.webView);
    WebSettings webSettings = mywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mywebView.loadUrl("http://google.com/");
    mywebView.setWebViewClient(new WebViewClient());
    mywebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    });
    mywebView.setWebViewClient(new WebViewClient() {
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);
            findViewById(R.id.progress).setVisibility(View.VISIBLE);
        }

       public void onPageFinished(WebView view, String url) {
            findViewById(R.id.progress).setVisibility(View.GONE);
        }
    });
}
public void onBackPressed() {
    if(mywebView.canGoBack()){
        mywebView.goBack();
    } else {
        super.onBackPressed();
    }
}}

Solution

  •  mywebView.setWebViewClient(new WebViewClient() {
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
    
                super.onPageStarted(view, url, favicon);
                findViewById(R.id.progress).setVisibility(View.VISIBLE);
            }
    
           public void onPageFinished(WebView view, String url) {
                findViewById(R.id.progress).setVisibility(View.GONE);
            }
    
            public void onReceivedError(WebView webview, int i, String s, String s1)
            {
                webview.loadUrl("file:///android_asset/error.html");
            }
        });
    

    Finally I found the solution.