Search code examples
androidsecurityvideouriandroid-4.4-kitkat

Get file path from Uri from Video Chooser


In my app I start an Intent to pick a video file like this

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
startActivityForResult(intent, kVideoPickerRequestCode);

When it comes back i get the Uri like this:

if(resultCode == RESULT_OK) {
  if (requestCode == kVideoPickerRequestCode) {
    Uri selectedVideoURI = data.getData();
  }
}

This Uri seems to be fine for my VideoView. It plays back the picked video perfectly. But now I'd like to upload the video to a server and therefore need a File.

No matter how i try to convert the Uri to a String-Path, it fails... I read some SO posts on this like How to convert content:// Uri into actual file path? or FileNotFoundException when trying to upload a recorded video to server from Android app but it's just not working for me.

Code like this always returns NULL as the path:

public static String getRealPathFromUri(Activity activity, Uri contentUri) {
  String[] proj = { MediaStore.Images.Media.DATA };
  Cursor cursor = getActivity().getContentResolver().query(uri, proj,  null, null, null);
  int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index);
}

My test-device is running Android 4.4.2. Can it be that it's some security issue with KitKat?

Thanks for any helping hint!


Solution

  • Your Uri does not necessarily represent a file on the disk. It begins with content:// meaning it is served up by the content provider for that type of file.

    You don't actually need to use a file in the filesystem here (although, you can). What you want to do is stream the data from the content provider directly to the server.

    There are some good examples - I would try this one for how to do this, in the first section "How to access binary data of existing content providers"