Convert a file path to Uri in Android
I have an app where I capture a video using the camera. I can get the video's file path, but I need it as a Uri.
The file path I'm getting:
/storage/emulated/0/DCIM/Camera/20141219_133139.mp4
What I need is like this:
content//media/external/video/media/18576.
This is my code.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
// selectedImageUri = data.getData();
// Uri selectedImage = data.getData();
previewVideo();
tv1.setText(String.valueOf((fileUri.getPath())));
String bedroom=String.valueOf((fileUri.getPath()));
Intent i = new Intent();
i.putExtra(bhk1.BEDROOM2, bedroom);
setResult(RESULT_OK,i);
btnRecordVideo.setText("ReTake Video");
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
I need a Uri from the String variable bedroom
.
Please try the following code
Uri.fromFile(new File("/sdcard/sample.jpg"))
Normal answer for this question if you really want to get something like content//media/external/video/media/18576
(e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4
:
MediaScannerConnection.scanFile(this,
new String[] { file.getAbsolutePath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("onScanCompleted", uri.getPath());
}
});
Accepted answer is wrong (cause it will not return content//media/external/video/media/*
)
Uri.fromFile(file).toString()
only returns something like file///storage/emulated/0/*
which is a simple absolute path of a file on the sdcard but with file//
prefix (scheme)
You can also get content
uri using MediaStore
database of Android
TEST (what returns Uri.fromFile
and what returns MediaScannerConnection
):
File videoFile = new File("/storage/emulated/0/video.mp4");
Log.i(TAG, Uri.fromFile(videoFile).toString());
MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
(path, uri) -> Log.i(TAG, uri.toString()));
Output:
I/Test: file:///storage/emulated/0/video.mp4
I/Test: content://media/external/video/media/268927