android content provider sum query
Asked Answered
O

4

6

Is it possible to use getContentResolver().query() when I want sum(column)?

OR

Do I have to make raw query to db handle?

Overlarge answered 2/5, 2011 at 7:1 Comment(0)
O
4

OK, it seems that its not possible using getContentResolver().query(). I had to get db connection and make rawQuery.

 ContentProviderClient client =  getContentResolver().acquireContentProviderClient(AUTHORITY);
 SQLiteDatabase dbHandle= ((MyContentProvider)client.getLocalContentProvider()).getDbHandle();
 Cursor cursor = dbHandle.rawQuery("SELECT sum("+COLUM_NNAME+") FROM "+TABLE_NAME +" WHERE "+WHERE_CLAUSE , null);
 cursor.moveToFirst();
 int cnt =  cursor.getInt(0);
 cursor.close();
 cursor.deactivate();
 client.release();
Overlarge answered 3/5, 2011 at 16:22 Comment(0)
P
6

When providing the array of columns to ContentResolver.query, wrap the column name with the sum() function

String[] columns = new String[] { "sum(" + columnName + ")" };

Cursor cursor = getContentResolver().query(
    content_uri,
    columns,
    selection,
    selectionArgs,
    sort
);

cursor.moveToFirst();

int columnSum = cursor.getInt(0);
Platt answered 16/8, 2011 at 20:58 Comment(1)
this is not working Invalid column sum(duration) E/DatabaseUtils( 2917): at android.database.sqlite.SQLiteQueryBuilder.computeProjection(SQLiteQueryBuilder.java:523)Hedve
O
4

OK, it seems that its not possible using getContentResolver().query(). I had to get db connection and make rawQuery.

 ContentProviderClient client =  getContentResolver().acquireContentProviderClient(AUTHORITY);
 SQLiteDatabase dbHandle= ((MyContentProvider)client.getLocalContentProvider()).getDbHandle();
 Cursor cursor = dbHandle.rawQuery("SELECT sum("+COLUM_NNAME+") FROM "+TABLE_NAME +" WHERE "+WHERE_CLAUSE , null);
 cursor.moveToFirst();
 int cnt =  cursor.getInt(0);
 cursor.close();
 cursor.deactivate();
 client.release();
Overlarge answered 3/5, 2011 at 16:22 Comment(0)
A
3

ACCEPTED ANSWER IS WRONG

IT IS POSSIBLE IN CONTENTPROVIDER AS

 String[] columns = new String[] { "sum(" + columnName + ")" };

    Cursor cursor = getContentResolver().query(
        content_uri,
        columns,
        selection,
        selectionArgs,
        sort
    );
int columnSum = cursor.getInt(0);

Only mistake Tom did is he forget to do :

cursor.moveToFirst();
Almost answered 18/3, 2016 at 19:11 Comment(1)
That Tom always making mistakes ;PCilurzo
S
0

You could use the 'simpleQueryForLong()'-Method.

Selinski answered 2/5, 2011 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.