asf asf - 2 years ago 153
Android Question

Java: Cursor return null

I have a DB. There can be empty fields.
When I try to get value from empty field with cursor, I get NullPointerExeption.

I found solution with 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) {}


But I don't like it. Can there be more attractive solution?

Answer Source

if cursor object is null, then it will give null pointer exception. If your object is not null, then you can check the objects arguments are empty or null. In this way, you can do it.

if(cursor != null) {
    // cursors argument you can check here.
    if(cursor.getString(2) != null) {
        subject.setName(cursor.getString(2));
    }
    ---
    ---
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download