Search code examples
javaandroiduriandroid-contentresolvermediastore

how to view image through image id in android


I've got the image id in the MediaStore. How can I view the image in the gallery with the id? I currently use the following code:

    ContentResolver cr = context.getContentResolver();

    String columns[] = new String[]{  
        Media._ID, Media.DATA
    };
    Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, Media._ID+"=?", new String[]{id+""}, null);
    if(cursor.moveToNext()) {
        String imagePath = cursor.getString(cursor.getColumnIndex(Media.DATA));
        Uri imageUri = Uri.fromFile(new File(imagePath));

        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.addCategory(android.content.Intent.CATEGORY_DEFAULT);
        intent.setDataAndType(imageUri, "image/*");
        ((Activity)context).startActivity(intent);
    }

It works but it's too cumbersome. I think there should an easier way to do this. The key is to get the image Uri from the image id.


Solution

  • int imageID = cursor.getInt( cursor.getColumnIndex(MediaStore.Images.Media._ID) ); 
    
    Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
    

    To get the Uri from id use this code.

    private void getPhoneGalleryImages() {
    
        Cursor cursor = cr.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null,
                null, null);
        cr = getActivity().getContentResolver();
        if(cursor != null)
        {
            if (cursor.moveToFirst()) {
                do {
                    String id = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Thumbnails._ID));
                    String path = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
    }