Home > Software design >  Android Kotlin Fragments: ''Attempt to invoke virtual method on a null object reference�
Android Kotlin Fragments: ''Attempt to invoke virtual method on a null object reference�

Time:07-08

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.

CodePudding user response:

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.

  • Related