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?

Dim
  • 4,527
  • 15
  • 80
  • 139

2 Answers2

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;
}
tyczj
  • 71,600
  • 54
  • 194
  • 296
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..

Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
  • 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 – tyczj Sep 19 '13 at 16:29
  • 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.. – Praful Bhatnagar Sep 19 '13 at 16:31
  • As explained by [Doug Currie](http://stackoverflow.com/a/8618629/342618), getCount() is potentially a very expensive operation. Therefore I'd suggest it be avoided unless you need to get the total count. – ChrisD Mar 16 '14 at 15:12
  • 1
    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. – Noor Hossain Jan 02 '21 at 15:34