0
votes

I'm trying to open a WebView from my BottomNavBar using Coroutines, but I am getting this error:

java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'DefaultDispatcher-worker-1'. All WebView methods must be called on the same thread.

My code looks like the following:

class WebViewFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_web_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        openWebView()
    }

    private suspend fun showWebView(){
        if(webView != null){

            webView!!.webViewClient = WebViewClient()
            webView!!.webChromeClient = WebChromeClient()

            val webSettings = webView!!.settings
            webSettings.javaScriptEnabled = true

            webView!!.loadUrl("https://www.google.com")

            webView!!.webViewClient = object: WebViewClient(){
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    progressBar.visibility = View.VISIBLE
                    super.onPageStarted(view, url, favicon)
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    progressBar.visibility = View.GONE
                    super.onPageFinished(view, url)
                }
            }
        }
    }

    private fun openWebView(){
        runBlocking(Dispatchers.Default) {
            showWebView()
        }
    }
}

Is there a best approach to achieve this? And can WebViews be loaded on another thread rather the UI thread?

Thanks :

1

1 Answers

1
votes

Dispatchers.Default uses a thread pool under the hood, and as the exception is telling you the WebView expects to have its methods called from the same Thread, the UI Thread in this case.

Also, per the docs runBlocking should only be used by main functions and tests as it blocks the caller Thread until the coroutine completes.

And can WebViews be loaded on another thread rather the UI thread?

No, WebView methods should be called from the UI Thread