如果字符串值为null,则应用程序强制关闭

时间:2013-08-15 11:09:36

标签: android

如果字符串有值,我的代码工作正常。但是,如果字符串为null,则会发生应用程序强制关闭。如何处理空字符串值?请帮帮我。

String value;
int value1;
String completedate;
e01 = (Button) findViewById(R.id.e01);

    case R.id.e01:
        value = e01.getText().toString();
        if (value != null) {
            value1 = Integer.parseInt(value);

            completedate = String.format("%02d", value1) 
                         + String.format("%02d", mMonth) 
                         + mYear;

            Toast.makeText(this, url +completedate, Toast.LENGTH_SHORT).show();
         } else {
            Toast.makeText(this, "Date not Available", 
            Toast.LENGTH_SHORT).show();
        // string is Null......
         }
         break;

1 个答案:

答案 0 :(得分:2)

这就是问题所在。

假设您的按钮文字为""(无文字)。调用value = e01.getText().toString();时,value现在的值为""(空字符串,非空)。 因此,它满足if条件。然后,它会尝试将""解析为Integer,这将为您提供NumberFormatException,然后强制关闭您的应用。

     value=e01.getText().toString();
     if(value!=null){

           value1 =Integer.parseInt(value);

如果您确定Button的文本是整数,那么您必须简单地将if条件更改为

if(!value.equals(""))

但是如果Button的文本可能是某个非整数值,请使用try-catch

    try{
        value1 =Integer.parseInt(value);

        // parsed successfully

        completedate=  String.format("%02d", value1) +   String.format("%02d",   
        mMonth)  +mYear;

        Toast.makeText(this, url +completedate, Toast.LENGTH_SHORT).show();

    }catch(NumberFormatException e){
        // value cannot be parsed to an integer

        Toast.makeText(this, "Date not Available", 
        Toast.LENGTH_SHORT).show();
    }