Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 275
Vinodh Kumar Avatar asked Dec 22 '14 12:12

Vinodh Kumar


People also ask

How do I change the path of a file in android?

url. toString() return a String in the following format: "file:///mnt/sdcard/myPicture.jpg", whereas url. getPath() returns a String in the following format: "/mnt/sdcard/myPicture.

How do I change my URL to URI?

The getURI() function of URL class converts the URL object to a URI object. Any URL which compiles with RFC 2396 can be converted to URI. URLs which are not in the specified format will generate an error if converted to URI format. Parameter: This method do not accept any parameter.

Can a URI be a path?

NET (for example, the method new Uri(path) ) generally uses the 2-slash form; Java (for example, the method new URI(path) ) generally uses the 4-slash form.

What is the format of Uri in Android?

Represents a Uniform Resource Identifier (URI) reference. Aside from some minor deviations noted below, an instance of this class represents a URI reference as defined by RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax, amended by RFC 2732: Format for Literal IPv6 Addresses in URLs.


Video Answer


3 Answers

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))
like image 113
Ganesh AB Avatar answered Oct 05 '22 21:10

Ganesh AB


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

like image 38
user924 Avatar answered Oct 05 '22 19:10

user924


If you want to Get Uri path from String File path .this code will be worked also in androidQ.

String outputFile = context.getExternalFilesDir("DirName") + "/fileName.extension";

            File file = new File(outputFile);
            Log.e("OutPutFile",outputFile);
            Uri uri = FileProvider.getUriForFile(Activity.this,
                    BuildConfig.APPLICATION_ID + ".provider",file);

declare provider in application Tag manifest

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

under res -> xml ->provider_paths.xml

<paths>
    <external-path name="external_files" path="."/>
</paths>
like image 29
Qamar khan Avatar answered Oct 05 '22 21:10

Qamar khan