0

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.

1
  • How many records are in the cursor? Commented Mar 10, 2013 at 0:52

2 Answers 2

1

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

Comments

0

Use do->while to start from first record

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.