Android Q 中 ContentResolver 查询中 "GROUP BY" 的替换( Android 10、API 29 更改)

Replacement for "GROUP BY" in ContentResolver query in Android Q ( Android 10, API 29 changes)

我正在升级一些遗留目标 Android Q,当然这段代码停止工作了:

       String[] PROJECTION_BUCKET = {MediaStore.Images.ImageColumns.BUCKET_ID,
            MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.DATA,
            "COUNT(" + MediaStore.Images.ImageColumns._ID + ") AS COUNT",
            MediaStore.Files.FileColumns.MEDIA_TYPE,
            MediaStore.MediaColumns._ID};

        String BUCKET_GROUP_BY = " 1) and " + BUCKET_WHERE.toString() + " GROUP BY 1,(2";

        cur = context.getContentResolver().query(images, PROJECTION_BUCKET,
            BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);

android.database.sqlite.SQLiteException: near "GROUP": syntax error (code 1 SQLITE_ERROR[1])

这里它应该获取包含相册名称、日期、图片数量的图像列表 - 每个相册一张图像,因此我们可以在不查询所有图片的情况下创建相册选择器屏幕并循环创建相册。

由于 SQL 查询停止工作,是否可以使用 contentResolver 对查询结果进行分组?

(我知道 ImageColumns.DATA 和 "COUNT() AS COUNT" 也已弃用,但这是关于 GROUP BY 的问题)

(有查询相册和单独查询照片的方法,获取相册封面的照片uri,但我想避免开销)

不幸的是,Group By 在 Android 10 及更高版本中不再受支持,也不支持任何聚合函数,例如 COUNT。这是设计使然,没有解决方法。

解决方案是您实际上试图避免的,即查询、迭代和获取指标。

要开始使用,您可以使用下一个片段,它将解析存储桶(相册)以及每个存储桶中的记录数量。

我没有添加代码来解析缩略图,但是很简单。您必须对所有相册实例中的每个存储桶 ID 执行查询,并使用第一条记录中的图像。

public final class AlbumQuery
{
    @NonNull
    public static HashMap<String, AlbumQuery.Album> get(@NonNull final Context context)
    {
        final HashMap<String, AlbumQuery.Album> output     = new HashMap<>();
        final Uri                               contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        final String[] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.BUCKET_ID};

        try (final Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null))
        {
            if ((cursor != null) && (cursor.moveToFirst() == true))
            {
                final int columnBucketName = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
                final int columnBucketId   = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID);

                do
                {
                    final String bucketId   = cursor.getString(columnBucketId);
                    final String bucketName = cursor.getString(columnBucketName);

                    if (output.containsKey(bucketId) == false)
                    {
                        final int              count = AlbumQuery.getCount(context, contentUri, bucketId);
                        final AlbumQuery.Album album = new AlbumQuery.Album(bucketId, bucketName, count);
                        output.put(bucketId, album);
                    }

                } while (cursor.moveToNext());
            }
        }

        return output;
    }

    private static int getCount(@NonNull final Context context, @NonNull final Uri contentUri, @NonNull final String bucketId)
    {
        try (final Cursor cursor = context.getContentResolver().query(contentUri,
                null, MediaStore.Images.Media.BUCKET_ID + "=?", new String[]{bucketId}, null))
        {
            return ((cursor == null) || (cursor.moveToFirst() == false)) ? 0 : cursor.getCount();
        }
    }

    public static final class Album
    {
        @NonNull
        public final String buckedId;
        @NonNull
        public final String bucketName;
        public final int    count;

        Album(@NonNull final String bucketId, @NonNull final String bucketName, final int count)
        {
            this.buckedId = bucketId;
            this.bucketName = bucketName;
            this.count = count;
        }
    }
}

这是一种更有效(不完美)的方法。

我是为视频做的,但是做图片也是一样的。只需将 MediaStore.Video.Media.X 更改为 MediaStore.Images.Media.X

public class QUtils {
        /*created by Nasib June 6, 2020*/
        @RequiresApi(api = Build.VERSION_CODES.Q)
        public static ArrayList<FolderHolder> loadListOfFolders(Context context) {
            ArrayList<FolderHolder> allFolders = new ArrayList<>();//list that we need
            HashMap<Long, String> folders = new HashMap<>();  //hashmap to track(no duplicates) folders by using their ids
    
            String[] projection = {MediaStore.Video.Media._ID,
                    MediaStore.Video.Media.BUCKET_ID,
                    MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
                    MediaStore.Video.Media.DATE_ADDED};
    
            ContentResolver CR = context.getContentResolver();
    
            Uri root = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
    
            Cursor c = CR.query(root, projection, null, null, MediaStore.Video.Media.DATE_ADDED + " desc");
    
            if (c != null && c.moveToFirst()) {
                int folderIdIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_ID);
                int folderNameIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
                int thumbIdIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
                int dateAddedIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED);
    
                do {
                    Long folderId = c.getLong(folderIdIndex);

                    if (folders.containsKey(folderId) == false) { //proceed only if the folder data has not been inserted already :) 
                        long thumbId = c.getLong(thumbIdIndex);
                        String folderName = c.getString(folderNameIndex);
                        String dateAdded = c.getString(dateAddedIndex);
                        Uri thumbPath = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, thumbId);
                        folders.put(folderId, folderName);
                        allFolders.add(new FolderHolder(String.valueOf(thumbPath), folderName, dateAdded));
                    }

                } while (c.moveToNext());
    
                c.close(); //close cursor
                folders.clear(); //clear the hashmap becuase it's no more useful
            }
            return allFolders;
        }
    }

FolderHolder 模型 class

public class FolderHolder {
    private String folderName;
    public long dateAdded;
    private String thumbnailPath;
    public long folderId;

    public void setPath(String thumbnailPath) {
        this.thumbnailPath = thumbnailPath;
    }

    public String getthumbnailPath() {
        return thumbnailPath;
    }

    public FolderHolder(long folderId, String thumbnailPath, String folderName, long dateAdded) {
        this.folderId = folderId;
        this.folderName = folderName;
        this.thumbnailPath = thumbnailPath;
        this.dateAdded = dateAdded;
    }
    public String getFolderName() {
        return folderName;
    }

}