Android WebView randomly doesn't show content for the same link

Viewed 197

I have a link to the PDF or XML file. By default, a web view doesn't render such links. From another StackOverflow post, I figured out I need to wrap by link by google doc or google drive link (http://docs.google.com/viewer?url=myPDFLink). It works, the web view displays content but not in all cases. For the same link, the content randomly might be not displayed or be displayed. If the page is not displayed I can just retry several times and content displays. Cannot find a reason for such behavior. Even if the web view is blank, the onPageFinished callback is being called but not any error callbacks.

  • Update: onPageStarted is not being called but onPageFinished is being

WebViewClient:

 val webViewClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            updateOnBackPressedCallbackState()
            toolbarActivity?.setToolBarTitle(url)
            onPageStateListener?.onPageStarted(view, url)
        }
        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            progressBar?.visibility = View.GONE
            toolbarActivity?.setToolBarTitle(view.title)
            onPageStateListener?.onPageFinished(view)
        }

        override fun onReceivedError(
            view: WebView?,
            errorCode: Int,
            description: String?,
            failingUrl: String?
        ) {
            super.onReceivedError(view, errorCode, description, failingUrl)
        }

        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest?,
            error: WebResourceError?
        ) {
            super.onReceivedError(view, request, error)
        }

        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest?,
            errorResponse: WebResourceResponse?
        ) {
            super.onReceivedHttpError(view, request, errorResponse)
        }

        override fun onReceivedSslError(
            view: WebView?,
            handler: SslErrorHandler?,
            error: SslError?
        ) {
            super.onReceivedSslError(view, handler, error)
        }
    }

Settings:

    webViewer.webViewClient = webViewClient
    webViewer.settings.javaScriptEnabled = true
    webViewer.isHorizontalScrollBarEnabled = true
    webViewer.settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
1 Answers

Try to handle SSL errors within onReceivedSslError to proceed with the certificate

override fun onReceivedSslError(
    view: WebView?,
    handler: SslErrorHandler?,
    error: SslError?
) = 
    if (handler != null) {
        handler.proceed() 
    } else {
        super.onReceivedSslError(view, handler, error)
    }
Related