asprin asprin - 1 month ago 9
Java Question

cursor.getCount() returning 1 but should have returned 0

I have a query which is

SELECT SUM(amount) AS total FROM transactions WHERE transaction_date > 1477333800


For this query,
cursor.getCount()
is returning
1
. But when iterating through the cursor, the value is coming up null.

public Cursor getTotalForToday(long start)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM(amount) AS total FROM "+TRANSACTION_TABLE+" WHERE transaction_date > "+start, null);
return c;
}

Cursor cursor = db.getTotalForToday();
if(cursor.getCount() == 0) // this is evaluating to false
{
forToday.setText("Zero"); //forToday is TextView
}
else
{
while(cursor.moveToNext())
{
String total_today = cursor.getString(0); // this is returning null
forToday.setText(total_today);
}
}


PS: The data type of
amount
is integer in the table

If I query the same thing in SQLLite Firefox extension, I'm getting the following output
SS1

Ideally, the number of rows returned should have been 0, but I have no idea why it is returning as 1.
Here is the data in the table btw:
SS2

Answer

Aggregate SQL functions such as SUM() always return a result row. The result itself can be null.

Comments