Issue
I want to attach images or video files from the Android storage. When I select a video from the gallery, it returns the content uri path.
How do I get the file path with extension from the content URI?
I tried following code, but it returns null in lollipop:
void pickVideo() {
Intent videoIntent = new Intent(Intent.ACTION_GET_CONTENT);
videoIntent.setType("video/*");
startActivityForResult(videoIntent, PICK_VIDEO_FILE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_VIDEO_FILE:
Uri videoUri = data.getData();
String path = getRealPathFromURI(getContext(), videoUri);
Log.d("Video uri path", "path" + path);
if (mChooseFileDialogListener != null) {
mChooseFileDialogListener.onVideoClick(videoUri, HealthRecordViewModel.FILE_TYPE_VIDEO);
}
break;
}
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Video.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Solution
How to get the file path with extension?
You don't. There is no requirement that the user select a piece of content that is saved as a file in a place that you have read access to. And there is no requirement that a ContentProvider
offer some means of translating a Uri
to a file path.
Use ContentResolver
and openInputStream()
to read in the content identified by the Uri
.
Answered By - CommonsWare
Answer Checked By - David Marino (JavaFixing Volunteer)