当我点击数字键盘上的“完成”按钮时,应用程序崩溃了

时间:2014-01-26 22:38:27

标签: java android

我有这段代码:

    final EditText edC = (EditText) findViewById(R.id.etC);
    final String creditsS = edC.getText().toString().trim();
    final TextView tvD = (TextView) findViewById(R.id.tvDisplay); 

    tvD.setText("Enter amount of credits");

    edC.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            int credits = Integer.parseInt(creditsS);
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                tvD.setText("Your amount of credits" + credits);
                return true;
            }
            return false;
        }
    });

当我点击“完成”按钮时,应用程序崩溃了。我不明白问题出在哪里。请帮忙?感谢!!!

1 个答案:

答案 0 :(得分:1)

将您的代码更改为:

final EditText edC = (EditText) findViewById(R.id.etC);
final TextView tvD = (TextView) findViewById(R.id.tvDisplay); 

tvD.setText("Enter amount of credits");

edC.setOnEditorActionListener(new OnEditorActionListener() {

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        String creditsS = edC.getText().toString().trim();
        int credits = Integer.parseInt(creditsS);
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            tvD.setText("Your amount of credits" + credits);
            return true;
        }
        return false;
    }
});

它崩溃是因为你在有任何值之前从edC获取值,所以它试图解析一个空字符串并且它与NumberFormatException崩溃。