How to convert a content Uri into a File

pass the Uri to another activity and retrieve it

Your other activity does not necessarily have rights to work with the content identified by the Uri. Add FLAG_GRANT_READ_URI_PERMISSION to the Intent used to start that activity, and pass the Uri via the "data" facet of the Intent (setData()), not an extra.

To get the actual Path of the Uri

First, there is no requirement that the Uri that you get back be from the MediaStore.

Second, managedQuery() has been deprecated for six years.

Third, there is no requirement that the path that MediaStore has be one that you can use. For example, the audio file might be on removable storage, and while MediaStore can access it, you cannot.

How to convert a content Uri into a File

On a background thread:

  • Get a ContentResolver by calling getContentResolver() on a Context
  • Call openInputStream() on the ContentResolver, passing in the Uri that you obtained from ACTION_GET_CONTENT, to get an InputStream on the content identified by the Uri
  • Create a FileOutputStream on some File, where you want the content to be stored
  • Use Java I/O to copy the content from the InputStream to the FileOutputStream, closing both streams when you are done

Tags:

File

Uri

Android