views:

51

answers:

1

Hi.

I have a small Android app and currently I am firing a sql statement in android to get the count of rows in database for a specific where clause.

Following is my sample code:

public boolean exists(Balloon balloon) {
    if(balloon != null) {
        Cursor c = null;
        String count_query = "Select count(*) from balloons where _id = ?";
        try {
            c = getReadableDatabase().rawQuery(count_query, new String[] {balloon.getId()});
            if (c.getCount() > 0)
                return true;

        } catch(SQLException e) {
            Log.e("Running Count Query", e.getMessage());
        } finally {
            if(c!=null) {
                try {
                    c.close();
                } catch (SQLException e) {}
            }
        }
    }
    return false;
}

This method returns me a count 1 even when the database table is actually empty. I am not able to figure out; why that would happen. Running the same query in database gets me a count of 0.

I was wondering if it's possible to log or see in a log, all the sql queries that eventually get fired on database after parameter substitution; so that I can understand what's going wrong.

Cheers

+2  A: 

That query will always return one record (as will any SELECT COUNT). The reason is, that the record it returns contains a field that indicates how many records are present in the "balloons" table with that ID.

In other words, the one record (c.getcount()==1) is NOT saying that the number of records found in balloons is one, rather it is the record generated by Sqlite which contains a field with the result.

To find out the number of balloons, you should c.movetofirst() and then numberOfBalloons = c.getInt(0)

Brad Hein
Thanks a ton. That got me going in right direction.
Priyank