Android Select Multiple Video From Gallery Programmatically | Video Picker

android custom ratingbar, android change tab icon, android custom camera, android select multiple video from gallery

This tutorial is about Android Select Multiple Video From Gallery Programmatically.

We will create a video picker app today in the android studio.

Our app will be able to select or pick multiple videos from the gallery.

You can also use this example as an module of your existing app. Code is very simple to understand and integrate in any android studio project.

After selecting multiple videos, we will show two videos in the videoview as an example.

Follow below steps to learn about choosing multiple videos from gallery.

Proof of this android select multiple video from gallery tutorial

Consider following images which showcase the output of this example.

android select multiple video from gallery
First Screen
android select multiple video from gallery
Selecting Videos
android select multiple video from gallery
playing two videos

1. Read Permission

To read all the videos from the gallery of android device, we need read external storage permission.

Add below coding line in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

You can learn here how to programmatically request runtime permission in android.

2. Changing default activity

When you create new project in the android studio by default you have main activity.

Replace the code of activity_main.xml with below source code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <VideoView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/vv"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"/>
    <VideoView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/vv2"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:layout_marginTop="10dp"
        android:text="Select Multiple Videos From Gallery"/>

</LinearLayout>

In the above layout file, I have taken two videoviews and one button.

When the user will click the button, a new screen will appear. This screen shows all the videos available on the android device.

From here, user will select multiple videos or single video.

After completing selecting videos, app will come back to first screen.

Now among the multiple selected videos, first two videos will be shown in the two videoviews.

Replace the code of MainActivity.java with the following one

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.VideoView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private VideoView videoView, videoView2;
    private Button btn;
    private static final String TAG = "VideoPickerActivity";

    private static final int SELECT_VIDEOS = 1;
    private static final int SELECT_VIDEOS_KITKAT = 1;

    private List<String> selectedVideos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.btn);
        videoView = (VideoView) findViewById(R.id.vv);
        videoView2 = (VideoView) findViewById(R.id.vv2);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT <19){
                    Intent intent = new Intent();
                    intent.setType("video/mp4");
                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select videos"),SELECT_VIDEOS);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    intent.setType("video/mp4");
                    startActivityForResult(intent, SELECT_VIDEOS_KITKAT);
                }
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            selectedVideos = getSelectedVideos(requestCode, data);
            Log.d("path",selectedVideos.toString());
            videoView.setVideoPath(selectedVideos.get(0));
            videoView.requestFocus();
            videoView.start();

            if(selectedVideos.size() > 1) {
                videoView2.setVideoPath(selectedVideos.get(1));
                videoView2.requestFocus();
                videoView2.start();
            }
        }

    }

    private List<String> getSelectedVideos(int requestCode, Intent data) {

        List<String> result = new ArrayList<>();

        ClipData clipData = data.getClipData();
        if(clipData != null) {
            for(int i=0;i<clipData.getItemCount();i++) {
                ClipData.Item videoItem = clipData.getItemAt(i);
                Uri videoURI = videoItem.getUri();
                String filePath = getPath(this, videoURI);
                result.add(filePath);
            }
        }
        else {
            Uri videoURI = data.getData();
            String filePath = getPath(this, videoURI);
            result.add(filePath);
        }

        return result;
    }

    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

Button Click

Compiler will execute following code when the user clicks the button.

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT <19){
                    Intent intent = new Intent();
                    intent.setType("video/mp4");
                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select videos"),SELECT_VIDEOS);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    intent.setType("video/mp4");
                    startActivityForResult(intent, SELECT_VIDEOS_KITKAT);
                }
            }
        });

System will open a screen with all the videos to select via intent.

When the user finishes selecting videos system will run the below code

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            selectedVideos = getSelectedVideos(requestCode, data);
            Log.d("path",selectedVideos.toString());
            videoView.setVideoPath(selectedVideos.get(0));
            videoView.requestFocus();
            videoView.start();

            if(selectedVideos.size() > 1) {
                videoView2.setVideoPath(selectedVideos.get(1));
                videoView2.requestFocus();
                videoView2.start();
            }
        }

    }

Here, we will run one method called getSelectedVideos() which will return the string arraylist.

This arraylist contains all the paths of the selected videos.

Out of whole arraylist, we will pick first two paths and we will play videos in the two videoviews.

getSelectedVideos()

The code for getSelectedVideos() method is as below

 private List<String> getSelectedVideos(int requestCode, Intent data) {

        List<String> result = new ArrayList<>();

        ClipData clipData = data.getClipData();
        if(clipData != null) {
            for(int i=0;i<clipData.getItemCount();i++) {
                ClipData.Item videoItem = clipData.getItemAt(i);
                Uri videoURI = videoItem.getUri();
                String filePath = getPath(this, videoURI);
                result.add(filePath);
            }
        }
        else {
            Uri videoURI = data.getData();
            String filePath = getPath(this, videoURI);
            result.add(filePath);
        }

        return result;
    }

I have not used any third party github library in this tutorial.

Third party libraries are responsible for increasing apk size of the apk. So generally, I always try to use them as less as possible.

But if you still want to use any then consider the below links.

Here are some quick links which includes third party libraries.

Thank you very much for reading android select multiple video from gallery tutorial.

Have a nice day!

Download the Source Code

[sociallocker]Download Source Code For Select MultipleVideo Galley[/sociallocker]