【问题标题】:Android Studio: App crashes when numbers are not inputtedAndroid Studio:未输入数字时应用程序崩溃
【发布时间】:2016-05-14 04:41:35
【问题描述】:

当我输入数字时按钮工作正常,但当我不输入时它会崩溃。为了解决这个问题,我尝试使用条件语句,这样如果没有输入数字,计算按钮就不会运行,但它仍然不起作用。我放了一个 else 行看看它是否打印任何东西,但仍然没有。

        public void onClick(View view) {
            //This is where I tried to fix it
            if (percentageText.getText()!=null && numberText.getText()!=null){
                float percentage = Float.parseFloat(percentageText.getText().toString());
                float dec = percentage / 100;
                float total = dec * Float.parseFloat(numberText.getText().toString());
                totalTextView.setText(Float.toString(total));
                Log.d("myTag","Success!");
            } else {
               Log.d("myTag","Error no integer found");
            }
        }

这是日志: error

但是如果我解析 float 并不重要,因为 if 语句会阻止代码运行,对吧?还是它会尝试运行?

【问题讨论】:

  • 你试过用try-catch包围它吗?
  • 你能在这里发布 logcat 错误吗?
  • 您正在解析为float 这可能是问题所在。显示您的 logcat 以获取更多信息。
  • 尝试添加另一个条件检查以及空条件检查。 (numberText.getText().toString().trim().getlength > 0 ) 或 (!numberText.getText().toString().trim().equalignourcase("")) 将此应用于百分比编辑文本和数字文本编辑文本
  • @v-v 您的解决方案有效,谢谢!

标签: java android input crash


【解决方案1】:

尝试在空条件检查的同时添加另一个条件检查。

(numberText.getText().toString().trim().getlength > 0 ) or (! numberText.getText().toString().trim().equalignourcase("")) 

将此应用于百分比编辑文本和数字文本编辑文本

【讨论】:

    【解决方案2】:

    要强制在edittext中输入数字,可以将此属性设置为edittext:

    android:inputType="number"
    

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多