Loading video from gallery to VideoView through a button

4k views Asked by At

I am trying to load video from gallery to VideoView using a button. When I run my app, click on Load video button, it loads the video BUT plays only audio of that video file.

I've also added the READ_EXTERNAL_STORAGE permission in the manifest file.

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

This is my VideoView:

<VideoView
    android:layout_width="wrap_content"
    android:layout_height="250dp"
    android:id="@+id/videoView"
    android:layout_centerVertical="true"
    android:layout_alignParentStart="true" />

Please help me

My code:

public class MainActivity extends AppCompatActivity {
    VideoView videoField;
    Button LoadVid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LoadVid = (Button)findViewById(R.id.LoadVid);
        videoField = (VideoView)findViewById(R.id.videoView);
        LoadVid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, 0);
            }
        });
    }
    @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            Uri video = data.getData();
            videoField.setVideoURI(video);
            videoField.start();
        }
    }
}
1

There are 1 answers

0
Imran Aslam On

You should put setVideoURI code in try catch block like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK){
        Uri uri = data.getData();
        try{
            videoField.setVideoURI(uri);
            videoField.start();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

It should work now because I had it tested.