使用Content Resolver查询匹配指定媒体ID列表的音频数据异常排查
问题原因
你当前的代码存在两处核心错误:
- 查询条件使用了单值匹配的
=运算符,多ID匹配需要使用IN运算符,且要根据ID列表长度动态生成对应数量的占位符? - 选择参数传入格式错误:你将Long数组直接
toString后作为唯一参数传入,实际需要将每个ID转为字符串后作为独立参数项传入
修复代码
修改后的getSongsInPlaylist函数如下:
fun getSongsInPlaylist(songIds: List<Long>): List<Songs> { // 空ID列表直接返回 if (songIds.isEmpty()) return emptyList() val songList = mutableListOf<Songs>() // 1. 动态生成IN语句的占位符,有多少个ID就生成多少个? val placeholders = songIds.joinToString(separator = ", ") { "?" } val selection = "${MediaStore.Audio.Media._ID} IN ($placeholders)" // 2. 把每个Long类型ID转成String,作为查询参数数组 val selectionArgs = songIds.map { it.toString() }.toTypedArray() val collection = Utility.sdk29AndUp { MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL) } ?: MediaStore.Audio.Media.EXTERNAL_CONTENT_URI // 查询时直接传入生成好的参数数组即可 context.contentResolver.query( collection, projection, selection, selectionArgs, MediaStore.Audio.Media.DEFAULT_SORT_ORDER ).use { cursor -> if (cursor?.moveToFirst() == true) { do { val id = cursor.getLong(getColumnIndex(cursor, MediaStore.Audio.Media._ID)) val title = cursor.getString(getColumnIndex(cursor, MediaStore.Audio.Media.TITLE)) val artist = cursor.getString(getColumnIndex(cursor, MediaStore.Audio.Media.ARTIST)) // 原有截断标题、艺术家名的逻辑保留即可 songList.add( Songs( mediaId = id, title = title, subtitle = artist, ) ) } while (cursor.moveToNext()) } } return songList }
补充说明
- 不需要再使用全局的
selectionArgs成员变量,直接在函数内局部生成参数即可,避免变量复用导致的查询异常 - 所有传入
ContentResolver的参数都需要是String类型,所以要把Long类型的ID转为字符串再放到参数数组里
内容的提问来源于stack exchange,提问作者Ibccx
相关产品推荐
相关产品推荐

