【问题标题】:Why is my App crashing with a NullPointerException in my ButtonManager class?为什么我的应用程序在我的 ButtonManager 类中因 NullPointerException 而崩溃?
【发布时间】:2019-10-11 09:06:34
【问题描述】:

我正在制作一个小型测验游戏,我不想为每个 Activity 中的按钮制作每个功能,因为不要重复自己。但是当我启动我的应用程序时,它会因空指针异常而崩溃。

我在底部尝试了解决方案,并在 ButtonManager 类中创建了一个函数,其中我有一个 String 作为构造函数参数,并将其转换为上面命名的函数。

这就是我的 ButtonManager 类的样子:

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

    val button: Button = findViewById(buttonName)

    fun quitGame(){

        finish()
    }
}

这是我的函数调用在我的 Activity 中的样子:

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

这是错误代码:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

【问题讨论】:

  • 你调用 setcontentview 吗?
  • 不,我不叫它任何地方
  • 如果没有可见的布局,那么你不能使用“findviewbyId”,因为还没有视图。
  • ButtonManager(findViewById(R.id.buttonid))

标签: android kotlin nullpointerexception


【解决方案1】:

看起来您缺少一些 android 的基本概念。

我假设您只想为您的按钮添加一个点击监听器。在这种情况下,您根本不需要 Button 管理器类。

在您的活动中,您可以简单地添加:

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()
        }
    }
}

【讨论】:

  • 不,我不想为我的按钮添加点击监听器
猜你喜欢
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多