android content provider sum query

你离开我真会死。 提交于 2019-12-07 03:46:11

问题


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

OR

Do I have to make raw query to db handle?


回答1:


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);



回答2:


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();



回答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();



回答4:


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



来源:https://stackoverflow.com/questions/5854343/android-content-provider-sum-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!