1

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?

1
  • 1
    why dont you just String timeOut=null; ........ if(cursor..) timeOut=something; and check for if(timeOut==null) { } ? technically, creating an empty string to intialize it would be overhead anyway, since the object would not be used but created, as far as I know Commented Sep 3, 2013 at 13:45

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. timeOut == null worked. Will accept this as the answer since this got in first.
1

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

Comments

1

Yes... null instance have no methods..

SO you should initialize your variable timeOut==null;

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.