验证EditText值会崩溃应用程序

我有一个EditText(inputValue)接受numberDecimal格式,我需要验证。 验证功能被调用:

buttonCalculate.setOnClickListener { pickFunction() } 

如果这个EditText留空白,每次点击按钮后立即出现程序崩溃。 如果我填写零表单,然后点击按钮,验证按预期工作。

  fun pickFunction() { val s: String = inputValue.getText().toString().trim() val d = inputValue.getText().toString().toDouble() if(s.isNullOrEmpty()) { Toast.makeText(applicationContext, "Blank value entered", Toast.LENGTH_SHORT).show() return } if( d <= 0) { Toast.makeText(applicationContext, "Zero value entered", Toast.LENGTH_SHORT).show() return } // go do something with valid value } 

按钮点击让你崩溃,因为你的Edittext没有任何价值,你在空对象引用上调用.trim().toDouble() 。 调用trim和todouble方法之前,请检查null检查条件。

使用toDoubleOrNull()而不是toDouble()或在try-catch包装该行以处理NumberFormatException