【问题标题】:Toast in Try/Catch numberformatexception尝试/捕获数字格式异常中的 Toast
【发布时间】:2016-08-03 07:35:05
【问题描述】:

我想在我的 Try/Catch 中使用 Toast,但是当它捕获到错误的输入时,toast 不会出现。我在代码中找不到错误,请在这里帮助我。

这是包含 try/catch 块的代码的一小部分:

 else{
      try{
          Integer.parseInt(score_1.getText().toString());
          Integer.parseInt(score_2.getText().toString());
          ArrayList_matches.get(position_match).score_1 = score_1.getText().toString();
          ArrayList_matches.get(position_match).score_2 = score_2.getText().toString();
          adapter.notifyDataSetChanged();


      } catch(NumberFormatException ex) {
          Toast.makeText(Game_activity.this, "Wrong input, numbers only", Toast.LENGTH_LONG).show();
      }

     }

【问题讨论】:

  • 你应该使用 log.e(tag, message);

标签: android try-catch android-alertdialog toast numberformatexception


【解决方案1】:

这么简单的使用

Toast.makeText(getApplicationContext(), "Wrong input, numbers only", Toast.LENGTH_LONG).show();

而不是

Toast.makeText(Game_activity.this, "Wrong input, numbers only", Toast.LENGTH_LONG).show();

如果你想调试然后使用

Log.d("TAG","YOUR MSG");

【讨论】:

    【解决方案2】:

    为 score1 设置一些默认整数值。

    【讨论】:

      【解决方案3】:

      试试这个方法

       try {
      
           Integer.parseInt(score_1.getText().toString());
           Integer.parseInt(score_2.getText().toString());
           ArrayList_matches.get(position_match).score_1 = score_1.getText().toString();
           ArrayList_matches.get(position_match).score_2 = score_2.getText().toString();
           adapter.notifyDataSetChanged();
      
       } catch(NumberFormatException ex) {
      
           runOnUiThread(new Runnable(){
           public void run() {
               Toast.makeText(Game_activity.this, "Wrong input, numbers only", Toast.LENGTH_LONG).show();
           });
      
       }
      

      我强烈建议在 catch 中使用 Log

      编码愉快。

      【讨论】:

        【解决方案4】:

        可能不是 NumberFormatException。请输入非数字格式的错误输入,

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-13
          • 2011-12-05
          • 2014-05-11
          • 2017-10-06
          • 1970-01-01
          • 2020-10-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多