1

I use this function to get specific data from SQlite:

SearchRes getSresultByName(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
            KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
            new String[] { name }, null, null, null, null);

    if (cursor != null)
        cursor.moveToFirst();

    SearchRes searchres = new SearchRes(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));

    return searchres;
}

And it works just fine, I need to create similar function to test if value is exist in the table, so I tried this:

boolean checkIfExist(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
            KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
            new String[] { name }, null, null, null, null);


    if (cursor == null)
        return false;

    else
        return true;

}

But I always get TRUE. Can you help me figure out what is the problem?

1

2 Answers 2

6

you should not be checking if cursor is null you should be checking if anything exists in the cursor

if(cursor.moveToFirst()){
    return true
}else{
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

3

You can try Cursor getCount() to check the number of rows in the result of the query.. Following is the sample code:

boolean checkIfExist(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
            KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
            new String[] { name }, null, null, null, null);


    if (cursor.getCount() > 0)
        return true;

    else
        return false;

}

answer by @tyczj is also good..

4 Comments

doing this is redundant because if there is a count > 0 then you have to call movetoFirst() anyway or else you will get an out of bounds error
agree.. but the purpose of the method is not to read data but to check if data exists.. and as I mentioned in my answer.. both approaches are good..
As explained by Doug Currie, getCount() is potentially a very expensive operation. Therefore I'd suggest it be avoided unless you need to get the total count.
But, I checked for null in Cursor, but there were exceptions shown in catch block when cursor count is 0, but, after applying the above method now fine, thanks for the approach.

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.