比较字符串时可以为空

时间:2016-06-05 17:39:07

标签: java android string-comparison

我正在尝试从包含响应代码“00,02”的服务器获得响应我使用if和else if语句为每个响应执行操作但是获取第一个if的空指针声明

if (str.equalsIgnoreCase("02")){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else{
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}

3 个答案:

答案 0 :(得分:6)

比较字符串的无效安全方法是:

if ("02".equalsIgnoreCase(str)) {
    ...
}

所以只需在每个条件下翻转琴弦,你就应该好好去吧!

答案 1 :(得分:0)

像这样更新你的条件

if(str == null || str.length() == 0){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
else if (str.equalsIgnoreCase("02")){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
else{
    // Unknown code from server
}

答案 2 :(得分:0)

您可以使用TextUtils.isEmpty(str)功能,如下所示:

if (!TextUtils.isEmpty(str)){

    if (str.equalsIgnoreCase("02")){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }else if(str.equalsIgnoreCase("00")){
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }else{
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }
}

此功能基本上适用于您:

public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0)
        return true;
    else
        return false;
}

你可以自己做,但这样可能会更清楚。