Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify in onActivityResult if image was selected from gallery or video was selected - Android

I am using following code to select a image or video from gallery :

    imgGallery.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent pickPhoto = new Intent(Intent.ACTION_GET_CONTENT);
                    pickPhoto.setType("*/*");
                    String[] mimetypes = {"image/*", "video/*"};
                    pickPhoto.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                    startActivityForResult(pickPhoto,
                            SELECT_PICTURE_OR_VIDEO);
                }
            });

Please note I am using same button for image or video selection. So when onActivityResult will be called, is there any way from which I can know that a image was selected or video was selected from the gallery?

like image 235
rahul Avatar asked Dec 28 '15 06:12

rahul


2 Answers

Using the path as suggested by the other answers here isn't the best way of doing this because there is no guarantee that the path will always include the words images / video on all versions of Android on all devices forever.

Instead try using Content Resolver to get the mime type:

ContentResolver cr = mContext.getContentResolver();
String mime = cr.getType(uri);

You can use it like this

public void onActivityResult(int requestCode, int resultCode, Intent mediaReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, mediaReturnedIntent);

    Uri selectedMedia = mediaReturnedIntent.getData();
    ContentResolver cr = mContext.getContentResolver();
    String mime = cr.getType(selectedMedia);
    if(mime.toLowerCase().contains("video")) {
        // Do something with the video
    } else if(mime.toLowerCase().contains("image")) {
        // Do something with the image
    }
}
like image 179
365SplendidSuns Avatar answered Sep 19 '22 01:09

365SplendidSuns


You can check with below code.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && data.getData() != null) {
        String path = data.getData().getPath();
        if (path.contains("/video/")) {
            Log.d(this.getClass().getName(), "Video");
        } else if (path.contains("/images/")) {
            Log.d(this.getClass().getName(), "Image");
        }
    }
}

This will work definitely because the path which we will get is something like I didn't find anything other than this, this will work definitely because the path it returns something like this /external/images/media/2928 where we will not get any repetitive data. Because the URI here only contains the ID of the image in the database of android data store.

like image 24
Nigam Patro Avatar answered Sep 18 '22 01:09

Nigam Patro