当一个可能为空时比较字符串

Comparing Strings when one could be null

我目前正在尝试从包含响应代码“00,02”的服务器获取响应第一个 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();
}

像这样更新你的条件

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
}

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

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

因此,只需翻转每个条件中的字符串,您就可以开始了!

您可以像这样使用 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;
}

您也可以自己完成,但这样可能更清楚。