Android Pick Single/Multiple Videos From Gallery Or Camera Programmatically

android custom dialog with edittext, android pick video from gallery or camera

Android Pick single or multiple Video from gallery or camera Programmatically tutorial with example is for you here.

The definition of this example is to select/get single or multiple videos from gallery and show it in the videoview.

1. Android Pick/Select Single Video from Gallery or Camera

2. Android Select/Pick/Get Multiple Videos From Gallery Or Capture From Camera

1. Android Pick/Select Single Video from Gallery or Camera

This tutorial will also choose or take or capture the video from the camera and play this recorded video in the videoview.

We will also learn how to save the video (which is picked up from the gallery) in the internal storage. After recording or capturing the video from camera, we will save it in the internal storage.

You will get to know how to get video path from gallery in android studio. We will get the video path from uri.

Now follow all the steps to complete this android pick video from gallery or camera tutorial.

After all coding practice you should get the output like below images.

android pick video from gallery or camera
Screen 1
Screen 2
android pick video from gallery or camera
Screen 3
android pick video from gallery or camera
Screen 4
Screen 5
android pick video from gallery or camera
Screen 6

Step 1. Giving Permissions

Give below three permissions in the android manifest file.

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

We are storing video in the internal storage, so first two permissions are regarding this.

Last one is giving permission to use the camera of the android device.

If your app is targeting the sdk version greater than 22, then you must ask for runtime permissions.

I have set the target sdk version as “22“, so I do not need to ask for the runtime permissions in this tutorial.

Step 2. Coding Final Lines

Add below source code into activity_main.xml file

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Select or Capture Image" />
 <VideoView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/vv"/>
   
</LinearLayout>

One button and one videoview is present here.

Button is used to decide whether to pick video from gallery or camera and videoview will play the selected the video for the reference.

Copy and paste following source code into MainActivity.java file

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
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.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private VideoView videoView;
    private static final String VIDEO_DIRECTORY = "/demonuts";
    private int GALLERY = 1, CAMERA = 2;

    @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);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPictureDialog();
            }
        });

    }

    private void showPictureDialog(){
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "Select video from gallery",
                "Record video from camera" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                chooseVideoFromGallary();
                                break;
                            case 1:
                                takeVideoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }

    public void chooseVideoFromGallary() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, GALLERY);
    }

    private void takeVideoFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        startActivityForResult(intent, CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.d("result",""+resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            Log.d("what","cancle");
            return;
        }
        if (requestCode == GALLERY) {
            Log.d("what","gale");
            if (data != null) {
                Uri contentURI = data.getData();

                String selectedVideoPath = getPath(contentURI);
                Log.d("path",selectedVideoPath);
                saveVideoToInternalStorage(selectedVideoPath);
                videoView.setVideoURI(contentURI);
                videoView.requestFocus();
                videoView.start();

            }

        } else if (requestCode == CAMERA) {
            Uri contentURI = data.getData();
            String recordedVideoPath = getPath(contentURI);
            Log.d("frrr",recordedVideoPath);
            saveVideoToInternalStorage(recordedVideoPath);
            videoView.setVideoURI(contentURI);
            videoView.requestFocus();
            videoView.start();
        }
    }

    private void saveVideoToInternalStorage (String filePath) {

        File newfile;

        try {

            File currentFile = new File(filePath);
            File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + VIDEO_DIRECTORY);
            newfile = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".mp4");

            if (!wallpaperDirectory.exists()) {
                wallpaperDirectory.mkdirs();
            }

            if(currentFile.exists()){

                InputStream in = new FileInputStream(currentFile);
                OutputStream out = new FileOutputStream(newfile);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;

                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
                Log.v("vii", "Video file saved successfully.");
            }else{
                Log.v("vii", "Video saving failed. Source file missing.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Video.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }

}

Let us learn all the above code blocks step by step.

First of all, required variables are declared.

private Button btn;
private VideoView videoView;
private static final String VIDEO_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;

Videoview and button is there in first two lines.

In the third line, folder name is there, in which, selected video will be saved.

Two constants are there in the fourth line.

Pay attention at below method

 private void showPictureDialog(){
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "Select video from gallery",
                "Record video from camera" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                chooseVideoFromGallary();
                                break;
                            case 1:
                                takeVideoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }

Above method will be called when the user clicks on the button.

After the button click, one dialog with two options will be opened. First option is to choose video from gallery and second is to capture video from the camera.

When the user select first option chooseVideoFromGallery() method is invoked.

On the selection of the second option takeVideoFromCamera() method is called.

Below is the code for chooseVideoFromGallery method.

public void chooseVideoFromGallary() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, GALLERY);
}

Method is very simple. One intent is created which will allow user to pick video from all the videos which are available on the android device.

Following is the code structure for takeVideoFromCamera method.

private void takeVideoFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        startActivityForResult(intent, CAMERA);
    }

I have also defined one intent here, which will allow user to record the video from the camera.

After choosing video from the gallery or taking video from the camera, compiler will call the onActivityResult() method.

Both method contains the request code. Request code for gallery is defined by the constant GALLERY(value is 1) and for camera(value is 2) it is CAMERA.

Here is the lines of code for onActivityResult method.

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.d("result",""+resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            Log.d("what","cancle");
            return;
        }
        if (requestCode == GALLERY) {
            Log.d("what","gale");
            if (data != null) {
                Uri contentURI = data.getData();

                String selectedVideoPath = getPath(contentURI);
                Log.d("path",selectedVideoPath);
                saveVideoToInternalStorage(selectedVideoPath);
                videoView.setVideoURI(contentURI);
                videoView.requestFocus();
                videoView.start();

            }

        } else if (requestCode == CAMERA) {
            Uri contentURI = data.getData();
            String recordedVideoPath = getPath(contentURI);
            Log.d("frrr",recordedVideoPath);
            saveVideoToInternalStorage(recordedVideoPath);
            videoView.setVideoURI(contentURI);
            videoView.requestFocus();
            videoView.start();
        }
    }

In this method compiler will check the scenario whether the video is coming from the gallery or camera using the request code.

Different Request Codes are there for both intents as we have seen earlier.

If the video is selected from the gallery, then compiler will go into the if(requestcode == GALLERY) condition otherwise in to the else if(requestcode == CAMERA) condition.

We have URI of the video at this level.

URI contains the data structure of the video.

To save the video on the internal storage we require path to the video.

Path to the video can be retrieved from the URI using getPath() method.

saveVideoToInternalStorage() method will save the video. For using this method we need to pass the path to the video in it’s parameter.

After getting the path and saving the video, compiler will start the video into the videoview.

So that was all the useful details for android pick video from gallery or camera example tutorial.

Hope you have found out what you were looking for.

If not then comment out, we will try to make new tutorial.





2. Android Select/Pick/Get Multiple Videos From Gallery Or Capture From Camera

This tutorial is about Android Select Multiple Videos 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 videos from gallery tutorial

Consider following images which showcase the output of this example.

android select multiple video from gallery
First Screen
Selecting Videos
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"/>

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!