0

当我的 edittext 上有 Int 并且按下 OK 按钮时,我正在强制关闭。

05-07 16:00:12.945: E/AndroidRuntime(28366): java.lang.NumberFormatException: 无法将“”解析为整数

这就是我得到的 logcat 错误。

这是代码:

//Button OK

Button bOK = (Button) findViewById(R.id.bOK);
bOK.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

        Toast invalid = Toast.makeText(getApplicationContext(), "Only values between 0-255 will be accepted.", Toast.LENGTH_LONG);
        uin = Integer.parseInt(value.getText().toString());

        if ( uin <= 255 ) {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec("su");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            try {
                os.writeBytes("chmod 644 sys/class/leds/button-backlight/brightness\n");
                os.writeBytes("echo " +uin+ " > sys/class/leds/button-backlight/brightness\n");
                os.writeBytes("chmod 444 sys/class/leds/button-backlight/brightness\n");
                os.writeBytes("exit\n");
                os.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if ( uin > 255 ) {
            invalid.show(); 
        }
    }
});

EditText如果(uin missing) 显示 toast上没有值输入,我如何告诉应用程序,而不是强制关闭?:D

请对我温柔,这是我使用java和android的第二周,我之前从未有过任何编程语言经验:)

4

4 回答 4

1

你需要包围线 uin = Integer.parseInt(value.getText().toString()); 像这样的 try/catch 块

try {
    uin = Integer.parseInt(value.getText().toString());
} catch(NumberFormatException e){
    //do something here
}
于 2012-05-07T14:11:31.520 回答
0

set your Edittext in .xml

android:inputType="number" 

and try to enclose with Try-catch block like

try {
    uin = Integer.parseInt(value.getText().toString());   
} catch(Exception e) {
    e.printStackTrace();
}

using e.printStackTrace(); u can find which Exception occur at this stage.

于 2012-05-07T14:20:27.153 回答
0

也许您应该捕获抛出的异常:

try {
    uin = Integer.parseInt(value.getText().toString());
} catch (NumberFormatException exception) {
    //What to do if the exception is thrown...
    [... Your code ...] 
}
于 2012-05-07T14:13:11.213 回答
0

只需检查您的editext是否为空,如果它是然后捕获异常,并且它没有继续执行您想要做的事情。

于 2012-05-07T14:11:18.850 回答