如果EditText为空,当我单击按钮时,应用程序崩溃



我写了一个简单的温度转换器应用程序,除了用户将EditText留空/为空但选择其中一个单选按钮时,一切都很好,应用程序崩溃。

这是Kotlin代码:

class MainActivity : AppCompatActivity() {
lateinit var etTemp: EditText
lateinit var radioGroup: RadioGroup
lateinit var btnConverter :Button
lateinit var tempConverted: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Zeeshan's Temperature Converter"
etTemp = findViewById(R.id.etTemp)
radioGroup = findViewById(R.id.radioGroup)
btnConverter = findViewById(R.id.btnConverter)
tempConverted = findViewById(R.id.tempConverted)
btnConverter.setOnClickListener {
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this@MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}

}
}
}

您应该检查etTemp.text.ToString((是否="quot;(那是空字符串(如果是,那么不要尝试将其转换为int;空";值到内部

在监听器内部添加一个检查EditText以检查它是否为空,

btnConverter.setOnClickListener {
// Add the validation check here ... like this -> if(etTemp.length() > 0){
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this@MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
// Close the check here -> }
else{
//     Prompt the user to put some text in the field - this is called form validation before processing
//     Toast.makeText(.....).show
}

}

检查用户是否输入了一些输入,有一种方法如下(Kotlin(:

if(!etTemp.text.isNullOrEmpty())
{
temp =etTemp.text.toString().toInt()
}

最新更新