Search code examples
androidkotlinandroid-webview

How can I override page not found net::ERR_ADDRESS_UNREACHABLE on Android Studio Kotlin WebViewClient or WebView?


I simply don't want users on my TV app to see the URL I'm using with the App when web page is unreachable. In that case they will get an error message with the URL:

"The webpage at http://example.com/action.php could not be loaded because: net::ERR_ADDRESS_UNREACHABLE" I tried to override fun onReceivedError as follows:

public class MyWebViewClient(activity: MainActivity) : WebViewClient() {
private val activity = activity
@SuppressWarnings("deprecation")
override  fun  onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
    //super.onReceivedError(view, errorCode, "No internet!", "failingUrl") //Here I supressed super.
    Toast.makeText(activity, "onReceivedError! errorCode=$errorCode description: $description url: $failingUrl", Toast.LENGTH_LONG).show()
} 

}

The Toast is displayed but the error message still displays, so I'm guessing there is some other function that I need to override. I am usin AVD (55" Android TV 1080p) with API 22 (Android 5.1)

What am I missing here? please advise, thank you.


Solution

  • For some reason that is unknown to me, if you do not override the function in a specific way, which is provide an alternative error HTML page, default android error page will keep popping up. I was able to get to this conclusion after finding an answer to a similar question as mine here: enter link description here

    So my Kotlin code now looks like this:

        val wedData: String =  "<html><body><h1>No Internet!</h1></body></html>"
        val mimeType: String = "text/html"
        val utfType: String = "UTF-8"        
        var mWebView : WebView
        mWebView = findViewById(R.id.web_view)
        mWebView.setWebViewClient(object : WebViewClient() {
            override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
               // mWebView.loadUrl("file:///android_asset/myerrorpage.html")
                mWebView.loadData(wedData,mimeType,utfType)
            }
        }) 
    mWebView.apply {
                
                var postData = "user=" + URLEncoder.encode("user", "UTF-8") + "&mode="+URLEncoder.encode("client", "UTF-8")
                settings.javaScriptEnabled = true            
                settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
                postUrl("http://example.com/", postData.encodeToByteArray())
            }