How do I get the _count in my content provider?

后端 未结 4 826
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 17:32

What should I do to get my content provider to return the _count column with the count of records? The documentation says it is automatic, but maybe it\'s only taking about

相关标签:
4条回答
  • 2020-12-13 18:11

    If you are using ContentProvider.query() a Cursor is returned. Call Cursor.getCount() to get a count of records in the returned cursor.

    0 讨论(0)
  • 2020-12-13 18:12

    If you are using contentProvider then you have to do it like count(*) AS count.

    If you use cursor.getCount(), that would not be as efficient as the above approach. With cursor.getCount() you are fetching all the records just to get counts. The entire code should look like following -

     Cursor countCursor = getContentResolver().query(CONTENT_URI,
                    new String[] {"count(*) AS count"},
                    null,
                    null,
                    null);
    
            countCursor.moveToFirst();
            int count = countCursor.getInt(0);
    

    The reason why this works is because android needs a column name to be defined.

    0 讨论(0)
  • 2020-12-13 18:15

    With cursor.getCount() you can not assure that it returns the real number of items returned. There are much better ways:

    1- If you are using Content Providers, you can do a query and use the Column (_COUNT) included in BaseColumns for your projection

    @Override
    public Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        ...
    
        projection = new String[] {
            ContentContract.NotificationCursor.NotificationColumns._COUNT,
        };
    
        ...
    
        Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder);
        return cursor;
    }
    

    2- To do a rawQuery using SELECT COUNT(*) as @saurabh says in his response.

    0 讨论(0)
  • 2020-12-13 18:20

    I had a similiar problem and found this worked for me. In the example below I wanted to get the count of images from the MediaStore provider.

            final String[] imageCountProjection = new String[] {
                    "count(" + MediaStore.Images.ImageColumns._ID + ")",
            };
    
            Cursor countCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    imageCountProjection,
                    null,
                    null,
                    null);
    
            countCursor.moveToFirst();
            int existingImageCount = countCursor.getInt(0);
    
    0 讨论(0)
提交回复
热议问题