我有一个数据库。可以有空字段。当我尝试使用光标从空字段中获取值时,我得到NullPointerException
.
我找到了带有 try-catch 的解决方案:
try {
subject.setName(cursor.getString(2));
} catch (NullPointerException e) {}
try {
subject.setTrainer(cursor.getString(3));
} catch (NullPointerException e) {}
try {
subject.setLocation(cursor.getString(4));
} catch (NullPointerException e) {}
但我不喜欢它。还有比这更有吸引力的解决方案吗?
如果游标对象为空,则它将给出空指针异常。如果对象不为 null,则可以检查对象参数是否为空或 null。这样,你可以做到。
if(cursor != null) {
// cursors argument you can check here.
if(cursor.getString(2) != null) {
subject.setName(cursor.getString(2));
}
---
---
}
if (cursor != null)
{
subject.setName(cursor.getString(2));
subject.setTrainer(cursor.getString(3));
subject.setLocation(cursor.getString(4));
}
这行得通吗?首先检查以确保光标不为空?
像
这样检查空值:
if (cursor != null) {//if cursor can achieve null value. I don't know your code before
String str2 = cursor.getString(2);
if (str2 != null) {
//...
subject.setName(str2);
}
}
要么:
-
subject
为空, -
cursor
为空,或 - 如果参数为 null,
subject.setName()
将引发NullPointerException
。
使用您提供的少量信息,无法说出哪个,但堆栈跟踪会告诉您。在没有try/catch
的情况下防御任何这些条件都很容易。
您可以在调用 getString(index) 之前检查空值。
if( !cursor.isNull(2) ){
subject.setName(cursor.getString(2));
}
有关更多详细信息,请查看此处的 API。