Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android content provider sum query

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

OR

Do I have to make raw query to db handle?

like image 262
Rahul Avatar asked May 02 '11 07:05

Rahul


2 Answers

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);
like image 171
Tom Curran Avatar answered Sep 29 '22 07:09

Tom Curran


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();
like image 22
Rahul Avatar answered Sep 29 '22 07:09

Rahul