这是我第一次构建android应用程序。但是,当我在虚拟设备上运行该应用程序时,它停止工作并不断崩溃。该错误说明了有关空指针异常的信息。这是我第一次使用Kotlin,并且用Java编写代码并更改为Kotlin。

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}

错误是:

最佳答案

似乎您忘记了初始化date editText。为什么不尝试Kotlin Android Extension plugin。通过使用此插件,您无需初始化 View ,而是可以使用其ID直接使用它们。对于您的情况:
只需添加导入

import kotlinx.android.synthetic.main.activity_add_sales.*

然后,您现在可以删除以下内容:
val date: EditText? = null
val changeDate: CheckBox? = null
val yes: RadioButton? = null
val no: RadioButton? = null

您可以通过其ID访问它们。喜欢
date.setText("15-11-2017")

关于android - 致命异常:主要KotlinNullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47344537/

10-12 00:25
查看更多