13

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?

1
  • I know nothing of Java or Android, but I can at least verify that the SQL is syntactically correct, and it will return the sum of all the numbers in COL_VALUES. Commented Jul 25, 2009 at 19:27

1 Answer 1

23

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.