views:

717

answers:

2

I'm new to SQLite and Java, and I'm trying to learn things on the fly. I have a column that has some numeric values in it, and I would like to get the sum of it and display it in a textview.

My current code is this:

public Cursor getTotal() {
    return sqliteDatabase2.rawQuery(
        "SELECT SUM(COL_VALUES) as sum FROM myTable", null);
}

I'm not sure if that code is correct, though.

I know that I'm supposed to fetch the results of that code, but I'm unsure how to do it. How can I get the results of this query into my Java code?

+4  A: 

The sum will be returned as a result with one row and one column so you can use the cursor to fetch that value:

Cursor cursor = sqliteDatabase2.rawQuery(
    "SELECT SUM(COL_VALUES) FROM myTable", null);
if(cursor.moveToFirst()) {
    return cursor.getInt(0);
}
Josef
A: 

I make a toast to print the result of cursor.getInt(0);

anda give me a exception saying empty values.. why dont give.me 0 ?

rui.pereira