I am working on a android studio project which is a hybrid of kotlin and java. I am trying to set an onClickListener to a button, however I keep running into compile time errors like the following:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.folioreader.android.sample/com.folioreader.ui.activity.FolioActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
This is my code:
private var buttonBookmarks: Button? = null
//these two are in onCreate
var buttonBookmarks = findViewById<Button>(R.id.btn_bookmarks)
buttonBookmarks.setOnClickListener {
Toast.makeText(this, "Works", LENGTH_LONG).show()
}
I know that this is an easy question, however, I did not have any experience with Kotlin before starting to work on this so I find it a bit confusing. Some online solutions I have tried did not work so I am asking the question here. What is wrong with my code?