0

I'm making a small Quiz Game and I didn't want to make every function for the Buttons in every Activity, because don't repeat yourself. But when I launch my App it crashes with a Null Pointer Exception.

I tried the Solution at the Bottom and aswell created a function in the ButtonManager class where I had as constructor parameter a String and converted it in the function named above.

This is what my ButtonManager class looks like:

class ButtonManager(buttonName: Int) : AppCompatActivity() {

    val button: Button = findViewById(buttonName)

    fun quitGame(){

        finish()
    }
}

This is what my functions call looks like in my Activity:

ButtonManager(R.id.quitGameButton).button.setOnClickListener {
    ButtonManager(R.id.quitGameButton).quitGame()
}

This is the Error Code:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
RKRK
  • 1,284
  • 5
  • 14
  • 18

1 Answers1

0

Looks like you are missing some fundamental concepts for android.

I assume you just want to add a clicklistener to your button. In that case you don't need your Button manager class at all.

In your Activity you can simply add:

class MyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?){

        setContentView(R.layout.your_layout) // xml layout with a Button with android:I'd=" @+I'd/quitGameButton"

        val button: Button = findViewById(R.id.quitGameButton)
        button.onClickListener{
                finish()
        }
    }
}
Entreco
  • 12,738
  • 8
  • 75
  • 95