没有值强制的Edittext关闭我的应用程序

时间:2012-05-07 14:07:40

标签: android integer android-edittext

当我的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)show toast上没有值输入,而不是强行关闭? :d

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

4 个答案:

答案 0 :(得分:1)

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

try {
    uin = Integer.parseInt(value.getText().toString());
} catch(NumberFormatException e){
    //do something here
}

答案 1 :(得分:0)

只需检查您的edittext是否为空,如果是,则捕获异常,如果它没有继续执行您想要执行的操作。

答案 2 :(得分:0)

也许你应该抓住引发的异常:

try {
    uin = Integer.parseInt(value.getText().toString());
} catch (NumberFormatException exception) {
    //What to do if the exception is thrown...
    [... Your code ...] 
}

答案 3 :(得分:0)

将您的Edittext设置为.xml

android:inputType="number" 

并尝试使用类似

的Try-catch块进行封闭
try {
    uin = Integer.parseInt(value.getText().toString());   
} catch(Exception e) {
    e.printStackTrace();
}

使用e.printStackTrace();你可以找到在这个阶段发生的异常。