Android: Get file path from Uri of file in SD card

Android: Get file path from Uri of file in SD card

To get the file path from a Uri pointing to a file on an SD card in Android, you can use the following approach:

Step-by-Step Guide

  1. Handle Permissions: Ensure you have the necessary permissions to read external storage. Add this in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
  2. Request Runtime Permissions: For Android 6.0 (API level 23) and above, request permissions at runtime.

  3. Get File Path from Uri: Use a method to resolve the Uri to a file path.

Example Code

Here's how you can implement this:

import android.Manifest import android.content.ContentResolver import android.content.Context import android.database.Cursor import android.net.Uri import android.os.Bundle import android.provider.MediaStore import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { private val REQUEST_CODE = 100 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Check for permissions if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE) } // Example URI (replace with your actual Uri) val uri: Uri = Uri.parse("content://media/external/audio/media/1") val filePath = getRealPathFromUri(this, uri) // Use the file path println("File Path: $filePath") } private fun getRealPathFromUri(context: Context, uri: Uri): String? { var cursor: Cursor? = null val projection = arrayOf(MediaStore.Audio.Media.DATA) try { cursor = context.contentResolver.query(uri, projection, null, null, null) if (cursor != null && cursor.moveToFirst()) { val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA) return cursor.getString(columnIndex) } } catch (e: Exception) { e.printStackTrace() } finally { cursor?.close() } return null } } 

Explanation

  • Permissions: Always ensure you have the required permissions to access external storage.
  • Querying the URI: Use ContentResolver to query the Uri and retrieve the file path.
  • Cursor Handling: Check if the cursor is not null and move it to the first record to fetch the file path.

Summary

  • This method retrieves the file path from a Uri for files located on an SD card or in external storage.
  • Always handle permissions properly, especially for Android 6.0 and above.

By following these steps, you can effectively get the file path from a Uri in your Android application!

Examples

  1. Get Real Path from Uri (Simple Uri Scheme) Description: Retrieving the real file path from a Uri when the file is located on external storage like SD card.

    public String getRealPathFromUri(Uri uri) { String filePath = ""; String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); filePath = cursor.getString(columnIndex); cursor.close(); } return filePath; } 
  2. Handling Uri with Content Scheme Description: Resolving the real file path from a Uri with the "content" scheme for files on external storage.

    public String getPathFromUri(Context context, Uri uri) { String filePath = ""; String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); filePath = cursor.getString(columnIndex); cursor.close(); } return filePath; } 
  3. Using DocumentFile for SAF (Storage Access Framework) Uri Description: Handling SAF Uri to retrieve file path for files on SD card using DocumentFile.

    public String getPathFromUri(Context context, Uri uri) { String filePath = ""; if (DocumentsContract.isDocumentUri(context, uri)) { DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri); filePath = documentFile.getUri().getPath(); } return filePath; } 
  4. Handling Uri with FileProvider (Scoped Storage) Description: Accessing file path from Uri when using FileProvider for accessing files in external storage.

    public String getRealPathFromUri(Context context, Uri uri) { String filePath = ""; if (DocumentsContract.isDocumentUri(context, uri)) { String documentId = DocumentsContract.getDocumentId(uri); String[] split = documentId.split(":"); String type = split[0]; Uri contentUri = MediaStore.Files.getContentUri(type); String selection = MediaStore.Files.FileColumns._ID + "=?"; String[] selectionArgs = new String[] { split[1] }; Cursor cursor = context.getContentResolver().query(contentUri, null, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA); filePath = cursor.getString(columnIndex); cursor.close(); } } return filePath; } 
  5. Handling Uri with Scoped Storage (Android 10+) Description: Obtaining the file path from Uri using MediaStore for files on SD card with scoped storage.

    public String getRealPathFromUri(Context context, Uri uri) { String filePath = ""; if (DocumentsContract.isDocumentUri(context, uri)) { String documentId = DocumentsContract.getDocumentId(uri); Uri contentUri = MediaStore.Files.getContentUri("external"); String selection = MediaStore.Files.FileColumns._ID + "=?"; String[] selectionArgs = new String[] { documentId }; Cursor cursor = context.getContentResolver().query(contentUri, null, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA); filePath = cursor.getString(columnIndex); cursor.close(); } } return filePath; } 
  6. Handling Uri with CursorLoader Description: Using CursorLoader to retrieve file path from Uri on external storage (SD card).

    public String getPathFromUri(Context context, Uri uri) { String filePath = ""; String[] projection = { MediaStore.Images.Media.DATA }; CursorLoader cursorLoader = new CursorLoader(context, uri, projection, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); filePath = cursor.getString(columnIndex); cursor.close(); } return filePath; } 
  7. Handling Uri with FileDescriptor Description: Using FileDescriptor to obtain file path from Uri for files on SD card.

    public String getRealPathFromUri(Context context, Uri uri) { String filePath = ""; try { ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); if (parcelFileDescriptor != null) { FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); FileInputStream inputStream = new FileInputStream(fileDescriptor); File file = new File(context.getCacheDir(), "temp_file"); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); filePath = file.getAbsolutePath(); inputStream.close(); outputStream.close(); parcelFileDescriptor.close(); } } catch (IOException e) { e.printStackTrace(); } return filePath; } 
  8. Using Uri.getPath() Description: Directly retrieving the file path from Uri using getPath() method.

    public String getPathFromUri(Uri uri) { return uri.getPath(); } 
  9. Handling Uri with TreeUri Description: Handling TreeUri to retrieve file path for files on SD card using DocumentFile.

    public String getPathFromUri(Context context, Uri uri) { String filePath = ""; if (DocumentsContract.isTreeUri(uri)) { DocumentFile documentFile = DocumentFile.fromTreeUri(context, uri); filePath = documentFile.getUri().getPath(); } return filePath; } 
  10. Handling Uri with UriResolver Description: Using ContentResolver to resolve file path from Uri for files on SD card.

    public String getPathFromUri(Context context, Uri uri) { String filePath = ""; Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); filePath = cursor.getString(index); cursor.close(); } return filePath; } 

More Tags

datatable.select percentile ftp laravel-mail venn-diagram sql-drop datetimeindex android-fullscreen uidatepicker angular-forms

More Programming Questions

More Trees & Forestry Calculators

More Housing Building Calculators

More Transportation Calculators

More Chemical reactions Calculators