与null比较,在java中不工作



我一直在尝试与null比较如果条件,但它不工作,总是去Else。下面是代码

String authEmail = cursor.getString(cursor.getColumnIndexOrThrow("AUTHOR_EMAIL"));
Log.i(gtag, "author email => " + authEmail);
    if (authEmail == null ) {
        Log.i(gtag, "in author check - IF NULL");
     } else {
            Log.i(gtag, "in author check - ELSE ");                 
     }

cursor是查询SQLite数据库的结果,AUTHOR_EMAIL是列名。Logcat显示作者电子邮件为空,但它仍然在ELSE中。以下是Logcat:

06-24 15:30:55.307: I/GCA-Abs-Con(1282): author email => foo@bar.de
06-24 15:30:55.307: I/GCA-Abs-Con(1282): in author check - ELSE 
06-24 15:30:55.357: I/GCA-Abs-Con(1282): author email => null
06-24 15:30:55.357: I/GCA-Abs-Con(1282): in author check - ELSE 

logcat的第三行显示authorEmailnull,但它仍然在else

我也试过authEmail.equals(null),但那也不起作用

我应该如何修改if条件来完美地检查null

要检查数据库字段是否具有SQL NULL值,请使用游标的isNull方法:

int index = cursor.getColumnIndexOrThrow("AUTHOR_EMAIL");
if (cursor.isNull(index)) {
    ...
} else {
    String authEmail = cursor.getString(index);
    ...
}

try this

  if (authEmail.equals("null")) {

代替

  if (authEmail == null ) {

使用.equals()进行字符串比较

这样做:

if (authEmail == null || authEmail.equals("null")) {
    ...
}

首先检查变量是否为空。如果不是,它检查string是否为文本null。当然,最好跟踪为什么字符串可以包含文本null,这看起来是无意的。

使用

if (authEmail == null || authEmail.equalsIgnoreCase("null")) {
  // handle null case
} else {
  // handle other case
}

最新更新