Vince
Vince

Reputation: 45

Adding data from a SQLite column

I'm, trying to add a credit score from multiple records of an SQLite table.

Each record has a column called credit score, I want to add them all together but I'm having trouble.

Here is the code:

String[] projection2 = { BorrowMeTable.COLUMN_CREDIT_SCORE };
Cursor databaseCursor2 = getContentResolver().query(uri, projection2,
        null, null, null);
int number  = 0;
if (databaseCursor2 != null) {
    databaseCursor2.moveToFirst();
    while (databaseCursor2.moveToNext()) { 
        number = number + databaseCursor2.getInt(
                databaseCursor2.getColumnIndexOrThrow(
                        BorrowMeTable.COLUMN_CREDIT_SCORE));
    }
}
Log.d("SCORE", Integer.toString(number));

The problem is the while statement, when it is in place it doesn't pull any data. When I remove it, it pulls the correct data but only from one record.

Upvotes: 0

Views: 56

Answers (2)

AwadKab
AwadKab

Reputation: 3064

Use do->while to start from first record

  do{
    number = number + databaseCursor2.getInt(
            databaseCursor2.getColumnIndexOrThrow(
                    BorrowMeTable.COLUMN_CREDIT_SCORE));
}while (databaseCursor2.moveToNext());

Upvotes: 0

Moog
Moog

Reputation: 10193

Use the sum funstion in SQLite

Cursor cursor = sqliteDatabase2.rawQuery(
    "SELECT SUM(COLUMN_CREDIT_SCORE) FROM BorrowMeTable", null);

You can URI match this in your ContentProvider as a different URI

Then simply get the scalar value:

if(cursor.moveToFirst()) {
    return cursor.getInt(0);

Upvotes: 1

Related Questions