How To Get Real File Path From Android Uri (2024)

12 Comments/ Android Tutorial / Android Content Provider

The previous article Android Pick Multiple Image From Gallery Example has told us how to browse an image gallery to select and show images use Intent.ACTION_GET_CONTENT intent. In that example, we save all user-selected images android file path URI in a list. Then we display those images one by one.

1. How To Select Android Documents By File Type Extension.

  1. Besides image type files, the Intent.ACTION_GET_CONTENTintent can be used to pick up any android documents with any file type extension.
  2. What you need to do is just invoke the Intent.ACTION_GET_CONTENTobject’s setType method and pass the file type extension string to it.
  3. For example, to select an android file of any document type, just pass “*/*” to the intent object’s setType method like below.
    openAlbumIntent.setType("*/*");oropenAlbumIntent.setType("image/*");or openAlbumIntent.setType("video/*");
  4. Please note, you must use the above setType method to set at least one file type extension, otherwise, it will throw below exception.
    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT }

2. How To Get The Real File Path From Android URI.

  1. At some time, only save the image URI in the android app is not enough, because the image URI may be changed, or the image URI is not changed but its related image may be removed.
  2. In this case, we need to save the URI-related images in the android app folder. Then we can use it later such as display it or upload it to a web server, this can improve the Android app performance.
  3. To achieve the above goal, we need to get the image URI-related file’s real android file path, then we can use this local android file path to read the image and save a copy of the image to our app folder.
  4. Because from android SDK version 19, to make Android apps secure, android does not allow one Android app to access other app-created files from the android storage system directly.
  5. If your Android app wants to access other app-created files, you should get the file from its ContentProvider with a content URI.
  6. The ContentProvider URI is not a real android file path URI ( such as file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg), it is a content provider style URI ( such as content://media/external/images/media/1302716 ).
  7. So we should parse the content provider style URI to the real android file local path by query-related content provider ( image provider, audio provider, video provider, and document provider ).
  8. The below source code will show you how to get an android file real local storage path from it’s content provider URI.
    /* This method can parse out the real local file path from a file URI. */private String getUriRealPath(Context ctx, Uri uri){ String ret = ""; if( isAboveKitKat() ) { // Android sdk version number bigger than 19. ret = getUriRealPathAboveKitkat(ctx, uri); }else { // Android sdk version number smaller than 19. ret = getImageRealPath(getContentResolver(), uri, null); } return ret;}/*This method will parse out the real local file path from the file content URI. The method is only applied to the android SDK version number that is bigger than 19.*/private String getUriRealPathAboveKitkat(Context ctx, Uri uri){ String ret = ""; if(ctx != null && uri != null) { if(isContentUri(uri)) { if(isGooglePhotoDoc(uri.getAuthority())) { ret = uri.getLastPathSegment(); }else { ret = getImageRealPath(getContentResolver(), uri, null); } }else if(isFileUri(uri)) { ret = uri.getPath(); }else if(isDocumentUri(ctx, uri)){ // Get uri related document id. String documentId = DocumentsContract.getDocumentId(uri); // Get uri authority. String uriAuthority = uri.getAuthority(); if(isMediaDoc(uriAuthority)) { String idArr[] = documentId.split(":"); if(idArr.length == 2) { // First item is document type. String docType = idArr[0]; // Second item is document real id. String realDocId = idArr[1]; // Get content uri by document type. Uri mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; if("image".equals(docType)) { mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; }else if("video".equals(docType)) { mediaContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; }else if("audio".equals(docType)) { mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } // Get where clause with real document id. String whereClause = MediaStore.Images.Media._ID + " = " + realDocId; ret = getImageRealPath(getContentResolver(), mediaContentUri, whereClause); } }else if(isDownloadDoc(uriAuthority)) { // Build download URI. Uri downloadUri = Uri.parse("content://downloads/public_downloads"); // Append download document id at URI end. Uri downloadUriAppendId = ContentUris.withAppendedId(downloadUri, Long.valueOf(documentId)); ret = getImageRealPath(getContentResolver(), downloadUriAppendId, null); }else if(isExternalStoreDoc(uriAuthority)) { String idArr[] = documentId.split(":"); if(idArr.length == 2) { String type = idArr[0]; String realDocId = idArr[1]; if("primary".equalsIgnoreCase(type)) { ret = Environment.getExternalStorageDirectory() + "/" + realDocId; } } } } } return ret;}/* Check whether the current android os version is bigger than KitKat or not. */private boolean isAboveKitKat(){ boolean ret = false; ret = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; return ret;}/* Check whether this uri represent a document or not. */private boolean isDocumentUri(Context ctx, Uri uri){ boolean ret = false; if(ctx != null && uri != null) { ret = DocumentsContract.isDocumentUri(ctx, uri); } return ret;}/* Check whether this URI is a content URI or not.* content uri like content://media/external/images/media/1302716* */private boolean isContentUri(Uri uri){ boolean ret = false; if(uri != null) { String uriSchema = uri.getScheme(); if("content".equalsIgnoreCase(uriSchema)) { ret = true; } } return ret;}/* Check whether this URI is a file URI or not.* file URI like file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg* */private boolean isFileUri(Uri uri){ boolean ret = false; if(uri != null) { String uriSchema = uri.getScheme(); if("file".equalsIgnoreCase(uriSchema)) { ret = true; } } return ret;}/* Check whether this document is provided by ExternalStorageProvider. Return true means the file is saved in external storage. */private boolean isExternalStoreDoc(String uriAuthority){ boolean ret = false; if("com.android.externalstorage.documents".equals(uriAuthority)) { ret = true; } return ret;}/* Check whether this document is provided by DownloadsProvider. return true means this file is a downloaded file. */private boolean isDownloadDoc(String uriAuthority){ boolean ret = false; if("com.android.providers.downloads.documents".equals(uriAuthority)) { ret = true; } return ret;}/* Check if MediaProvider provides this document, if true means this image is created in the android media app.*/private boolean isMediaDoc(String uriAuthority){ boolean ret = false; if("com.android.providers.media.documents".equals(uriAuthority)) { ret = true; } return ret;}/* Check whether google photos provide this document, if true means this image is created in the google photos app.*/private boolean isGooglePhotoDoc(String uriAuthority){ boolean ret = false; if("com.google.android.apps.photos.content".equals(uriAuthority)) { ret = true; } return ret;}/* Return uri represented document file real local path.*/private String getImageRealPath(ContentResolver contentResolver, Uri uri, String whereClause){ String ret = ""; // Query the URI with the condition. Cursor cursor = contentResolver.query(uri, null, whereClause, null, null); if(cursor!=null) { boolean moveToFirst = cursor.moveToFirst(); if(moveToFirst) { // Get columns name by URI type. String columnName = MediaStore.Images.Media.DATA; if( uri==MediaStore.Images.Media.EXTERNAL_CONTENT_URI ) { columnName = MediaStore.Images.Media.DATA; }else if( uri==MediaStore.Audio.Media.EXTERNAL_CONTENT_URI ) { columnName = MediaStore.Audio.Media.DATA; }else if( uri==MediaStore.Video.Media.EXTERNAL_CONTENT_URI ) { columnName = MediaStore.Video.Media.DATA; } // Get column index. int imageColumnIndex = cursor.getColumnIndex(columnName); // Get column value which is the uri related file local path. ret = cursor.getString(imageColumnIndex); } } return ret;}

3. Load Selected Image Into Memory Issue.

3.1 Question.

  1. In my program, I get the selected image Uri object with the code data.getData(); and I can get the Uri related string value content://media/external/images/media/99, but how can I get the image file absolute path, I do not need to copy the image to a local app folder, I just want to load the image into memory. But when I reboot my mobile phone, the memory is also lost, can anyone give me some help? Thanks a lot.

3.2 Answer1.

  1. The example source code in this article has told you how to get an image file absolute path, you can load the image into memory with the absolute file path.
  2. If your app runs on an Android SDK version smaller than 19 then you can use the method getImageRealPath(), otherwise, you can use the method getUriRealPathAboveKitkat(), please read the 2 methods carefully.
  3. To fix your android device reboot issue, you can save the user-selected image absolute file path in a configuration file, and when the device reboots, you can get the user last time browsed image’s absolute file path from the configuration file and then display it. Wish this can give you some help.

4. How To Parse the URI To Get the Full File Path Of A File?

4.1 Question.

  1. In my code, I use the android.provider.MediaStore to get a music file’s full file path.
  2. This is ok when I select the file using the music player, but it does not work when I use the Astro file browser to select the music file. How to fix this problem, thanks.

4.2 Answer1.

  1. If your android SDK version is newer than oreo, then you can use the below method to get the music file’s full file path.
  2. First, you need to get the media object’s Uri object using it’s getData() method.
  3. Then create a File object with the above Uri object.
  4. Call the file object’s getPath() method to get it’s full path.
  5. And then split the file full path to remove the protocol part.
  6. Below is the example source code.
    // Get the music file Uri object.Uri uriObj = data.getData(); // Get the Uri object's path.String uriPath = uriObj.getPath();// Create a File object from the above Uri path.File file = new File(uriPath);// Get the full file path string of the file object.String fullFilePath = file.getPath();// Split the protocol and full file path in the above file path.final String[] split = fullFilePath.split(":");// Get the object's full file path string.String fullFilePathResult = split[1];

5. How To Get The Real Path By Invoking The Android Uri Object’s getPath() Method.

5.1 Question(2022/05/14).

  1. My source code will get an image file from an image gallery.
  2. But when the activity returned, I got a Uri data like content://media/external/images/1.
  3. And what I want is the real file path like /sdcard/image/1.png
  4. How can I do that? Thanks a lot.
  5. Below is the source code.
    // Create an intent object.Intent intent = new Intent();// Set the intent type.intent.setType("image/*");// The intent will open a file browser.intent.setAction(Intent.ACTION_GET_CONTENT);// Show a file browser to let the user to select file with the file type.startActivityForResult(Intent.createChooser(intent, "Select picture"), resultCode );

5.2 Answer1.

  1. I think it is not necessary to get the real physical path if you just want to use the file in your app.
  2. For example, if you just want to show the image in an ImageView object, you can follow the below steps.
  3. You can first get the image Uri object (call the data.getData() method) and then use the ImageView.setImageURI(uriObject) to show it.
  4. If you want to read the file content you can use the ContentResolver.openInputStream() method.
  5. But if you want to get the filename and extension, and then convert the image to a physical file, I think maybe you need to get the file real path, but you can give the file a new name also.

00votes

Article Rating

Subscribe

Login

This site uses Akismet to reduce spam. Learn how your comment data is processed.

12 Comments

Newest

OldestMost Voted

Inline Feedbacks

View all comments

How To Get Real File Path From Android Uri (2)

qwerty

Thank You VERYYY much !!! it workeddd !! i had no idea how to get path for a database file(.db) .. turns out it’s a “content” file and not a “file” file lol which kinda makes sense ig. but yeah THANK YOU

Reply

How To Get Real File Path From Android Uri (3)

Abhay

I was searching for this stuffs since two-three days. Thanks a lot. I almost gave up. Thanks a lot.

1

Reply

How To Get Real File Path From Android Uri (4)

ChanLung

Thank you.
But in android emulator (include Android 9.0) …..
Uri downloadUri = Uri.parse(“content://downloads/public_downloads”);
In this part, the issue was happened.
I hope you help me as soon as possible.
Best wishes

-1

Reply

How To Get Real File Path From Android Uri (5)

Kirill Karmazin

You shouldn’t try to get file path from Uri. Or at least you should understand that not all Uris can provide you with a file path!
read this: https://stackoverflow.com/a/49619018/5502121

The code above will crash if your Uri won’t have a ‘_data’ column in the cursor if it’s media.

For example, In my case user draws a picture, and it is saved as a Bitmap in .png file. I create a Uri using FileProvider and this Uri IS a MEDIA but DOESN”T HAVE the ‘_data’ column.

And the last thing: this code is very inefficient – you shouldn’t query with ‘null’ as a projection (the list of columns).

And there is a lot of such cases.

Reply

How To Get Real File Path From Android Uri (6)

UchePhilz

Why do I feel that there is a shorter way to get this done??

2

Reply

How To Get Real File Path From Android Uri (7)

David Chen

Jerry. Your code is wonderful. This helped me a lot with my school project. But how did you learn all this if the info is not in the Android documentation?

1

Reply

How To Get Real File Path From Android Uri (8)

Arko Chatterjee

Hey, Thank you for the code. It works for most apps but does not work for images shared from WhatsApp. I am trying to catch the images shared from WhatsApp to my app but the uri of the images does not give the real path. When i’m using your code it gives the error:

java.lang.IllegalStateException: Couldn’t read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly

Can you please suggest something to fix it.
Thank you

Reply

happyzhaosong

Admin

Reply toArko Chatterjee

From the error message, it said the col number is -1 which is not correct, because the minimum col value should be 0.

I think you should set a breakpoint at where the error occurred, and debug into it to fix this error.

Reply

How To Get Real File Path From Android Uri (10)

Marium

Reply toArko Chatterjee

Hey I am facing the same problem when trying to open the file shared on whatsapp. Have you found any solution?

Reply

How To Get Real File Path From Android Uri (11)

Ricardo

Super nice……. 1000/1000

Reply

How To Get Real File Path From Android Uri (12)

Alex Boutakidis

You are my hero, such a mess on documenting this on google’s part

-1

Reply

How To Get Real File Path From Android Uri (13)

Rob

Very helpful, thanks!!!

Reply

How To Get Real File Path From Android Uri (2024)

FAQs

How to get actual image path from uri in android? ›

Uri uri = data. getData(); File file = new File(uri. getPath());//create path from uri final String[] split = file. getPath().

How to convert URI to file path in Android? ›

Uri object which is named uri and created exactly as in the question, uri. toString() returns a String in the format "file:///mnt/sdcard/myPicture.jpg" , whereas uri. getPath() returns a String in the format "/mnt/sdcard/myPicture. jpg" .

How to get file path from uri in android 11? ›

You would use APIs like getDirectory() on StorageVolume to work with storage volumes (external and removable) via Android 11's "all files access". See this blog post for more. the blog says "With no permissions, your app can create files of any type in the Documents/ and Downloads/ directories.

How do I find Filepath on Android? ›

  1. Use path for internal storage String path="/storage/sdcard0/myfile. txt";
  2. path="/storage/sdcard1/myfile. txt";
  3. mention permissions in Manifest file. ...
  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......
Feb 18, 2015

How do I get a full image path? ›

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

Can a URI be a file path? ›

The single slash between host and path denotes the start of the local-path part of the URI and must be present. A valid file URI must therefore begin with either file:/path (no hostname), file:///path (empty hostname), or file://hostname/path .

What is URI parse in Android? ›

It is an immutable one-to-one mapping to a resource or data. The method Uri. parse creates a new Uri object from a properly formated String .

What is URI absolute path? ›

What is an absolute URL? An absolute URL is the full URL, including protocol ( http / https ), the optional subdomain (e.g. www ), domain ( example.com ), and path (which includes the directory and slug). Absolute URLs provide all the available information to find the location of a page.

How to get file path from URI in Android Oreo 8.1 or above? ›

Steps to Reproduce the Problem
  1. When picking file method is called, it displays the folders in Android.
  2. Go to downloads, select a file.
  3. It returns null in getting real path from URI.
Oct 12, 2018

How to get file path in android 11 programmatically? ›

If you are dealing with Media files (i.e. Images, Videos, Audio) you can get the file path by Using Media Store API that having support to API 30(Android 11). and If you are dealing with non-media files(i.e. documents and other files) you can get the file path by using file Uri.

How do I copy a file path on my phone? ›

Copy files from Storage devices section
  1. On your Android device, open Files by Google .
  2. At the bottom, tap Browse .
  3. Scroll to "Storage devices."
  4. Tap Internal storage.
  5. Find the folder with the files you want to copy.
  6. Find the files you want to copy. To copy one file: In grid view: Press and hold the file. ...
  7. Tap Copy here.

How do I get file path or code? ›

How to show full file path in Visual Studio Code
  1. Select File > Preference > Settings. Visual Studio Code Settings.
  2. Click on WORKSPACE SETTINGS. Visual Studio Code Workspace Settings.
  3. Type window.title into the search bar. ...
  4. Click on the pencil tool and select Copy to Settings. ...
  5. Set the title to ${dirty}${activeEditorLong}

How do I get the path of a file? ›

The file path is found at the top of the folder or webpage where you are viewing the file. For example: When viewing files in your web browser, the Google Drive file path is at the top of the Google Drive webpage.

How do I find the location of a file path? ›

Search File Explorer: Open File Explorer from the taskbar or right-click on the Start menu, choose File Explorer and then select a location from the left pane to search or browse. For example, select This PC to look in all devices and drives on your computer, or select Documents to look only for files stored there.

What is Imagepath? ›

A list of directories in which to look for image files. type: string, default: "" When specified by the image attribute or using the IMG element in HTML-like labels. imagepath should be a list of (absolute or relative) pathnames, each separated by a semicolon ; (for Windows) or a colon : (all other OS).

How do I make an image a full link? ›

This is an easy three-step process:
  1. Insert the image into the document.
  2. Right-click the image and select "Link" from the drop-down menu.
  3. Type or paste the hyperlink address into the "Address" field.

What is an absolute file path example? ›

An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

What can a URI turn into? ›

According to the American Lung Association, certain bacteria and viruses responsible for URIs can lead to pneumonia. The bacteria most often responsible for pneumonia are Streptococcus pneumoniae. Common viruses that can cause pneumonia include influenza and respiratory syncytial virus (RSV).

How can I get URI data? ›

3 Answers
  1. Right-click the image in question and choose Inspect Element.
  2. Right-click the image's URL (the cursor will turn into a hand) and choose Open link in Resources Panel.
  3. Right-click the image in the Resources Panel and choose Copy image as Data URL.
  4. Paste the Data URI wherever you need it.
Jun 8, 2012

Is a URI the same as a URL? ›

URL and URI, both crucial concepts of the web, are terms that are often interchanged and used. However, they are not the same. The URI can represent both the URL and the URN of a resource, simultaneously, while URL can only specify the address of the resource on the internet.

What is a URI query? ›

URI parameter (Path Param) is basically used to identify a specific resource or resources whereas Query Parameter is used to sort/filter those resources. Let's consider an example where you want identify the employee on the basis of employeeID, and in that case, you will be using the URI param.

What is URI in metadata? ›

For many of the metadata language elements, you can specify a metadata resource by its name or identifier. Some of the language elements accept a Uniform Resource Identifier (URI), which is a standard from SAS Open Metadata Architecture.

What is URI database? ›

A Uniform Resource Identifier (URI) is a unique sequence of characters that identifies a logical or physical resource used by web technologies. URIs may be used to identify anything, including real-world objects, such as people and places, concepts, or information resources such as web pages and books.

What is URL URI endpoint? ›

URI is the superset of URL. It comprises of protocol, domain, path, hash, and so on. It comprises of scheme, authority, path, query and many more.

What is a URI endpoint? ›

An endpoint URI is the URL of an external service that is accessed by a business service. In ALSB you must define at least one endpoint URI for a business service.

What are the 3 types of URL? ›

To recap, these are the three basic elements of a website URL:
  • The protocol – HTTP or HTTPS.
  • The domain name (including the TLD) that identifies a site.
  • The path leading to a specific web page.
May 13, 2022

How do I get access to all files on Android? ›

Find & open files
  1. Open your phone's Files app . Learn where to find your apps.
  2. Your downloaded files will show. To find other files, tap Menu . To sort by name, date, type, or size, tap More. Sort by. If you don't see "Sort by," tap Modified or Sort .
  3. To open a file, tap it.

How do I get Android app URI? ›

An easy way to obtain the proper URI for an Android app is to visit the app's page in the Google Play Store, tap the share button, and paste the copied link somewhere you can read it. The link will look like https://play.google.com/store/apps/details?id=com.twitter.android.

How do I open file manager in Android programmatically? ›

Intent intent = new Intent(Intent. ACTION_GET_CONTENT); intent. setType("*/*"); Intent i = Intent. createChooser(intent, "View Default File Manager"); startActivityForResult(i, CHOOSE_FILE_REQUESTCODE);

Why does Android 11 have restrictions file manager? ›

To protect user privacy, on devices that run Android 11 or higher, the system further restricts your app's access to other apps' private directories.

How can I open data folder in Android without root? ›

May be this is the first APP that can visit other app's exteral data file .
  1. Open folder "/storage/emulated/0/Android"​
  2. Click the"data" folder​
  3. Select the application you need​
  4. Click "Use this folder"​
  5. Done! ...
  6. Open folder "/storage/emulated/0/Android"​
  7. Click the"data" folder​
  8. Select the application you need​
Aug 16, 2022

What is Android path? ›

Path is an android class it is very useful or many time only choice in android for creating arbitrary shapes and drawings arbitrary figures , Path is also used in animations. But often times working with paths is very painful.

Is there a secret folder on Android? ›

You can hide files in your Safe folder and control access with a PIN. Tip: This feature is available for Android 8.0 and up.

Where are hidden vault apps on Android? ›

Finding hidden apps can be just as easy of “Show Hidden files” on Android devices, by going to the File Manager > All Files > open the menu > Settings > Show hidden files, or as complicated as trying to break the password for the Vault app.

How do I view private files on Android? ›

How to Find Hidden Files on Android
  1. Open your File Manager.
  2. Click "Menu," and then "Settings."
  3. Scroll to the "Advanced" section, and enable "Show hidden files."
  4. Then, all of the hidden files will be viewable and accessible.
  5. Go to the Gallery app on your Android device.
  6. Click on the "Gallery Menu."
  7. Choose "Settings."
Feb 16, 2023

How do I copy an image from URI? ›

Right click on an image preview within the Resources Panel to copy it as a Data URI (base 64 encoded).

How can I find the source of an image in Mobile? ›

The Chrome browser app for iOS and Android also supports a reverse-image search workaround. When you have the image you want to search, hold your finger on it until a pop-up menu appears; pick “Search Google for This Image” at the bottom.

How do I view an image from an API? ›

Display an Image from an API Response
  1. Open the request in the API tab on the right of the editor.
  2. Select the Events section. You should see an Event for each status code that the API returns.
  3. Open the Event for the status code your image URL is associated with (typically it will be 200: OK).
  4. Click the plus.
Dec 14, 2018

How to copy source code of Android app? ›

On Android, add view-source: to the beginning of the website URL. Tap and hold to highlight a word. Drag the bars to encompass all of the code. Tap Copy.

What does an image URI look like? ›

URI is an address like: http://www.google.com/image.png it refers to the image somewhere. So you can attach a file that you don't have on your device and you don't want to download it. Save this answer.

Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 6298

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.