简体   繁体   中英

Android Kotlin Fragments: ''Attempt to invoke virtual method on a null object reference''

My code in MainActivity:

    val buttonbckbrowse = findViewById<Button>(R.id.buttonbck)
    buttonbckbrowse.setOnClickListener {
        val webView = findViewById<WebView>(R.id.webViewBrowse)
        webView.goBack()
        Toast.makeText(baseContext, "Back", Toast.LENGTH_SHORT).show()
    }

buttonbck is in a different fragment.

When trying to run my app I get ''Exception: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference'' on the second line in the code above.

I can't figure out what I'm doing wrong.

Having an activity directly accessing a view of a fragment will always cause complications. I suggest you rethink you approach.

The fragment containing the button should set the click listener. When the button is clicked the fragment raises the event to an object shared with the hosting activity. (Something like WebViewNavigation) The hosting activity can then just set a click listener on WebViewNavigation to be triggered when the event is raised, or the WebViewNavigation can announce when an event occurs as a stream (using LiveData) and the activity can observe that stream of events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM