FileNotFoundException when trying to upload a recorded video to server from Android app

I’m trying to record a video and then upload it to a server upon its completion. Relevant code is here:

public void recordVideo(View view){
    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    startActivityForResult(takeVideoIntent, VIDEO_RESULT);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == VIDEO_RESULT){
        handleCameraVideo(data);
    }
}

private void handleCameraVideo(Intent intent) {
    Uri mVideoUri = intent.getData();
    File vidFile = new File(mVideoUri.getPath());
    RequestParams params = new RequestParams();
    try{
        params.put("video", vidFile);
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
        //finish upload here, this part isn't relevant to my question
}

The problem is that in my try block a FileNotFoundException gets thrown, and the stack trace prints out. It seems as though I should be getting the right file: I got most of the code up to the part where I make the File from the Android developer site, so it should work — which leads me to believe that the problem is at the File vidFile = new File(mVideoUri.getPath()); line. Any help would be appreciated.

Answer

I ended up finding another question on here that had some code that helped me out:

private String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

Then in my handleCameraVideo method:

private void handleCameraVideo(Intent intent) {
    Uri mVideoUri = intent.getData();
    String data = getRealPathFromURI(mVideoUri);
    File vidFile = new File(data);
 ....

This works and gets me the right file.

Leave a Reply

Your email address will not be published. Required fields are marked *