Convert a file path to Uri in Android Convert a file path to Uri in Android android android

Convert a file path to Uri in Android


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


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>