Home > Net >  How to implement WebVeiw in app "kotlin"?
How to implement WebVeiw in app "kotlin"?

Time:10-15

Trying to implement webView with kotlin but getting error Error 1 - java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.loadUrl(java.lang.String)' on a null object reference at com.abc.MainActivity.onNavigationItemSelected Error 2 - E/cr_PlatformSer-Internal: UsageReporting query failed E/cr_PlatformSer-Internal: Unable to determine Safe Browsing user opt-in preference

MainActivity.kt-

 val webView: WebView? = findViewById<WebView>(R.id.webView)

            webView?.webViewClient = WebViewClient()
            setContentView(R.layout.fragment_privacy)
            val url: String = intent.getStringExtra("https://www.geeksforgeeks.org/") ?: "Privacy"

privacyfragment.kt-

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

CodePudding user response:

You're trying to look for R.id.webView before you've set a layout on your Activity with setContentView. You need to do it in this order:

setContentView(R.layout.fragment_privacy)
val webView = findViewById<WebView>(R.id.webView)

That way findViewById can access the Activity's view (which has now been created) and do the search. Also, if you expect the WebView to be there, there's no need to make webView nullable - if it is null and causes a crash, it's because you have a problem that needs to be fixed.


But if you're trying to add a Fragment, calling setContentView with the fragment's layout XML won't do it - that just puts the same views in the Activity, there's no Fragment there. Read this guide to learn about Fragments and the different ways you can add them and navigate between them.

If you're creating a Fragment that holds your WebView, you should do all its setup (including the findViewById) inside the Fragment. Trying to poke at it from the Activity (and all the coordination that involves) will cause you a lot of problems. Your Activity can always call a function on the Fragment to request "load this URL", the Fragment itself should be the thing that talks directly to the WebView

CodePudding user response:

I was able to do it as

MainActivity.kt

setContentView(R.layout.fragment_privacy)
val webView = findViewById<WebView>(R.id.webView)
webView.webViewClient = WebViewClient()
            webView.settings.javaScriptEnabled = true
            webView.loadUrl("add your url here")
  • Related