【问题标题】:My App Stops When I Try To Get An Int当我尝试获取 Int 时,我的应用程序停止
【发布时间】:2012-09-22 20:35:17
【问题描述】:

我正在尝试制作一个接受输入并自动将其更改为 int 的应用。但是,当它尝试获取 int 时,应用程序会自动停止。以下是完整代码...

    public class MainActivity extends Activity implements OnClickListener{  

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button calculate = (Button)findViewById(R.id.calculateTip);
            calculate.setOnClickListener(this);

        }//end onCreate

    public void onClick(View v) {

            EditText money = (EditText)findViewById(R.id.bill);
            int bill = Integer.parseInt(money.getText().toString());
            money.setText("Event Processed");

    }//end onClick

    }//end MainActivity

【问题讨论】:

  • 您遇到什么错误?您也可以发布您的 XML 吗?
  • 你确定你发送的是整数而不是双精度吗?
  • 文本字段的内容是什么? LogCat 的输出是什么?

标签: java android parsing int


【解决方案1】:

我怀疑应用程序正在停止,因为您尝试解析的值并不是真正的整数。您应该将该代码放入 try catch。

即:

    public void onClick(View v) {

       EditText money;
       try
       {
            money = (EditText)findViewById(R.id.bill);

             // This check makes sure that the EditText is returning the correct object.
            if(money != null)
            {
              int bill = Integer.parseInt(money.getText().toString());
              money.setText("Event Processed");
            }
       }
       catch(NumberFormatException e)
       {
       // If we get in here that means the inserted value was not an Integer. So do               something.
       //ie:
        money.setText("Please enter a value amount" );
        }
    }//end onClick

无论如何,您应该在 try catch 中包含此代码以保持数据完整性。

希望这会有所帮助! 干杯。

【讨论】:

  • 如果您在onClick 方法中分配money 会有所不同吗?我通常只是在 onCreate 中分配 xml 引用
  • 我通常会把钱作为全局变量,然后在 onCreate 中赋值。使用 money 作为全局变量,您可以从类中的任何位置(例如 onClick)对其进行设置。此代码示例只是向您展示了您“可以”使用您提供的代码做什么。
【解决方案2】:

您确定 Object 是 EditText 的一个实例并且它不为空吗?

【讨论】:

  • .toString()应该没问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多