限制ContentResolver.query()函数中的行数

44

有没有办法限制游标返回的行数?我有一部手机大约有4000个联系人,但我只需要其中的一些。

这是我正在使用的代码

        db = new dBHelper(this);
        ContentResolver cr = getContentResolver();
        Cursor cursor;

        cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, ContactName + " ASC");
        Log.i(TAG, CLASSNAME + " got contacts entries");
        for (int it = 0; it <100 ; it++){//cursor.getCount()
            Log.i(TAG, CLASSNAME + " getting string");
            String mytimes_contacted = cursor.getString(cursor.getColumnIndex(dBHelper.times_contacted)); 
            Log.i(TAG, CLASSNAME + " done from the string");
        }

我得到的日志是

I/Check(11506): [ContactsPicker] got contacts entries
I/Check(11506): [ContactsPicker] getting first string
D/AndroidRuntime(11506): Shutting down VM
W/dalvikvm(11506): threadid=1: thread exiting with uncaught exception (group=0x2aac8578)
D/dalvikvm(11541): GC_CONCURRENT freed 923K, 46% free 4000K/7303K, external 1685K/2133K, paused 1ms+8ms
E/AndroidRuntime(11506): FATAL EXCEPTION: main
E/AndroidRuntime(11506): java.lang.RuntimeException: Unable to start activity ComponentInfo{~~my package name~~}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3537
5个回答

44

为了限制游标中的结果数量,请尝试:

cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, ContactName + " LIMIT 100");
while(cursor.moveToNext()) {
    // something clever
}

谢谢Sam,我完全忘记了在循环内移动光标,太愚蠢了!我会尝试你的建议并回来告诉你。 - user1347945
嗯,错误实际上是光标移动了,但好在我现在学会了如何限制光标。问题是,如何限制光标大小,以便即使数据库中的行数超过我指定的数量,我也可以获得有限的行数... - user1347945
19
请注意,这种方法并非适用于所有的“ContentProvider”。它假定了一种特定的实现方式(SQLite),并假设“ContentProvider”只会将值直接传递给SQLite。但这种情况并非总是成立的。 - CommonsWare
1
我们有一个 LG-G3 设备,它实现了 ContentProvider,但并不支持这里建议的 limit 子句,并以 ORDER BY LIMIT 50 结束查询。 - thepoosh
这也适用于短信提供程序 content://sms/inbox - v.ladynev
显示剩余4条评论

22

从Android 11开始,上述解决方案将无法使用,你可以尝试使用以下方法获取数据。

    /**
 * Call to fetch all media on device, it but be called synchronously since function is called on a background thread
 */
private fun fetchGalleryImages(
    context: Context,
    offset: Int,
    limit: Int
): List<MediaItem> {
    val galleryImageUrls = mutableListOf<MediaItem>()
    try {
        if (EasyPermissions.hasPermissions(
                context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {
            // Define the columns that will be fetched
            val projection = arrayOf(
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.DATE_ADDED,
                MediaStore.Files.FileColumns.MEDIA_TYPE,
                MediaStore.Files.FileColumns.MIME_TYPE,
                MediaStore.Files.FileColumns.TITLE,
                MediaStore.Video.Media.DURATION
            )
            val selection =
                "${MediaStore.Files.FileColumns.MEDIA_TYPE} = ? OR ${MediaStore.Files.FileColumns.MEDIA_TYPE} = ?"
            val selectionArgs = arrayOf(
                MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE.toString(),
                MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO.toString()
            )
            /**
             * Change the way to fetch Media Store
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Get All data in Cursor by sorting in DESC order
                context.contentResolver.query(
                    contentUri(),
                    projection,
                    Bundle().apply {
                        // Limit & Offset
                        putInt(ContentResolver.QUERY_ARG_LIMIT, limit)
                        putInt(ContentResolver.QUERY_ARG_OFFSET, offset)
                        // Sort function
                        putStringArray(     // <-- This should be an array. I spent a whole day trying to figure out what I was doing wrong
            ContentResolver.QUERY_ARG_SORT_COLUMNS,
            arrayOf(MediaStore.Files.FileColumns.DATE_MODIFIED)
        )

                        putInt(
                            ContentResolver.QUERY_ARG_SORT_DIRECTION,
                            ContentResolver.QUERY_SORT_DIRECTION_DESCENDING
                        )
                        // Selection
                        putString(ContentResolver.QUERY_ARG_SQL_SELECTION, selection)
                        putStringArray(
                            ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS,
                            selectionArgs
                        )
                    }, null
                )
            } else {
                val sortOrder =
                    "${MediaStore.Files.FileColumns.DATE_MODIFIED} DESC LIMIT $limit OFFSET $offset"
                // Get All data in Cursor by sorting in DESC order
                context.contentResolver.query(
                    contentUri(),
                    projection,
                    selection,
                    selectionArgs,
                    sortOrder
                )
            }?.use { cursor ->
                while (cursor.moveToNext()) {
                    galleryImageUrls.add(
                        MediaItem(
                            cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID)),
                            ContentUris.withAppendedId(
                                contentUri(),
                                cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID))
                            ),
                            cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)),
                            cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE)),
                            cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))
                        )
                    )
                }
            }
        }
    } catch (ex: Exception) {
        ex.printStackTrace()
    }
    return galleryImageUrls
}

1
谢谢,由于这个问题,在模拟器上我得到了一些意外的“无效令牌LIMIT”。 - JaviCasa
6
否则排序将不正确,您需要使用putStringArray(ContentResolver.QUERY_ARG_SORT_COLUMNS, new String[] { MediaStore.Files.FileColumns.DATE_MODIFIED })。 - artman
谢谢,Vo和@artman,你们两个都让我免于痛苦。 - zeroDivider

16

对于Android 11,已接受的答案不再有效。在Android 11中添加了一个约束条件,不允许在排序值中使用LIMIT。您需要使用带有bundle参数的查询。例如:

        val bundle = Bundle().apply {
            putInt(ContentResolver.QUERY_ARG_LIMIT, 100)
        }
        resolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                projection,
                bundle,
                null
        )

1
我无法找到更多关于此的信息/文档。我也在使用正常的查询路径(仅搜索特定路径)。 - Ben Butterworth

3

在 Android 26 中,query 方法得到了升级。该函数使用以下参数:

Uri uri,String[] projection,Bundle queryArgs,CancellationSignal cancellationSignal

下面的例子是获取最近的 5 张照片。

    val whereArgs = arrayOf("image/jpeg", "image/png", "image/jpg")

    val projection = arrayOf(MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.MIME_TYPE)


    val selection =
            "${MediaStore.Files.FileColumns.MIME_TYPE} = ? OR ${MediaStore.Files.FileColumns.MIME_TYPE} = ?  OR ${MediaStore.Files.FileColumns.MIME_TYPE} = ?"


    val queryArgs = Bundle()
    val sortArgs = arrayOf(MediaStore.Images.ImageColumns.DATE_TAKEN)

    queryArgs.putStringArray(ContentResolver.QUERY_ARG_SORT_COLUMNS, sortArgs)
    queryArgs.putInt(ContentResolver.QUERY_ARG_SORT_DIRECTION, ContentResolver.QUERY_SORT_DIRECTION_DESCENDING)
    queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 5)
    queryArgs.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, selection)
    queryArgs.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, whereArgs)

    val cursor = context!!.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            projection,
            queryArgs,
            null)


    if (cursor!!.moveToFirst()) {
        do {
            val imageLocation = cursor.getString(1)
            val imageFile = File(imageLocation)

            if (imageFile.exists()) {
              //access you file from imageLocation
            }
        } while (cursor.moveToNext())
        fiveRecentlyImagesAdapter!!.notifyDataSetChanged()
    }

1
如果有人正在寻找上述Ignacio Tomas Crespo答案的Java版本,
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {

            cursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                            .buildUpon()
                            .encodedQuery("limit=" + offSet + "," + "100")
                            .build(),
                    columns,
                    null,
                    null,
                    null);
        } else {
            Bundle bundle = new Bundle();
            bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, 100);

            cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            columns,
                            bundle,
                            null);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接