asf asf - 6 months ago 26
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

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));
    }
    ---
    ---
}