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.

4

2 回答 2

1

在 SQLite 中使用 sum 函数

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

您可以在 ContentProvider 中将 URI 匹配为不同的 URI

然后简单地获取标量值:

if(cursor.moveToFirst()) {
    return cursor.getInt(0);
于 2013-03-10T00:58:33.853 回答
0

使用 do->while 从第一条记录开始

  do{
    number = number + databaseCursor2.getInt(
            databaseCursor2.getColumnIndexOrThrow(
                    BorrowMeTable.COLUMN_CREDIT_SCORE));
}while (databaseCursor2.moveToNext());
于 2013-03-10T03:09:55.197 回答