Razgriz
Razgriz

Reputation: 7343

Android - string.equals(null) returns null pointer even when string was initialized

I am doing this database operation in my application where I pull a certain column value to check if it exists. I have no problems executing the query and assigning the value to a string (I can even output this value in the Log). My problem arises when I try to check if my string is equal to null, ironically, I'm getting a NullPointer.

Here is my function:

public boolean isDone(String id){
    boolean isDone = false;
    String timeOut = new String();
    timeOut = "A";

    String query = "SELECT TimeOut FROM " + TABLE_ROUTE_TABLE + " WHERE _id = '" + id + "'";
    Cursor cursor = mDB.rawQuery(query, null);

    if(cursor.moveToFirst()){
        timeOut = cursor.getString(cursor.getColumnIndex("TimeOut"));
        Log.d("Hi", "timeOut = " + timeOut);
    }

    if(timeOut.equals(null)){
        isDone = false;
    }
    else{
        isDone = true;
    }

    return isDone;
}

I am getting the NPE at if(timeOut.equals(null)). I don't understand why I am getting an NPE when I put the string as part of a boolean condition when I am able to use it and display its value (which may sometimes be null).

I have a feeling I'm overlooking something basic. Any ideas?

Upvotes: 1

Views: 2504

Answers (4)

Andres
Andres

Reputation: 6200

The null checking should be done on this way:

 if(timeout == null)

Because you want to know if the object even exists, that means, if the pointer is null or not. The content of a string cannot be null but the pointer to it can be null.

Upvotes: 1

Piyush
Piyush

Reputation: 18923

Yes... null instance have no methods..

SO you should initialize your variable timeOut==null;

Upvotes: 1

Wakoo
Wakoo

Reputation: 11

The issue is the equals compare 2 string together, since one of them is null, you get the NPE.

You can fix it by just testing

timeOut == null

Upvotes: 1

Mauren
Mauren

Reputation: 1975

If your timeOut variable is null, this test will always cause a NPE, because null instances have no methods. You should be testing with == operator, e.g. timeOut == null.

Why it is null, however, I can't understand, since you say it has value when printed.

Upvotes: 2

Related Questions