Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: construct a File from an android.net.URI

Tags:

android

I have an android.net.URI object (of the kind returned by onActivityResult after MediaStore.ACTION_VIDEO_CAPTURE): it looks like content://media/video/media/33.

I want to convert this into a File object, and only a File object - I need to pass it to another constructor that requires a File.

How can I convert a URI like this to a File object? If I try

File newFile = new File(myURI);

I get an error in Eclipse suggesting that I should convert the URI to a String. Supplying URI.getPath() in the constructor doesn't help either.

This relates to the 'How can I convert android.net.uri object to java.net.uri object?' question, which unfortunately seems to have no good answer, but I want a File object out, not a java uri.

I don't mind if I have to write it to a bytestream and back again - whatever is the best way.

Apologies if I'm cross-posting my own question, but I thought I might need to make things a bit clearer.

like image 956
AP257 Avatar asked Feb 28 '10 20:02

AP257


People also ask

How do I get a URI file?

To get the data type of a shared file given its content URI, the client app calls ContentResolver. getType() . This method returns the file's MIME type. By default, a FileProvider determines the file's MIME type from its filename extension.

What is an android URI?

A URI is a uniform resource identifier while a URL is a uniform resource locator.

What does URI Parse do in Android?

A Uri object is usually used to tell a ContentProvider what we want to access by reference. 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 .


1 Answers

How can I convert a URI like this to a File object?

You can't, in a reliable, SDK-compliant fashion.

"If the table entry is a content: URI, you should never try to open and read the file directly (for one thing, permissions problems can make this fail). Instead, you should call ContentResolver.openInputStream() to get an InputStream object that you can use to read the data. "

(from http://developer.android.com/guide/topics/providers/content-providers.html)

You will need to modify the other code to accept and utilize an InputStream. Or, if the other code is supposed to be modifying the data, it will need to use an OutputStream, a topic also covered in the page linked to above.

like image 95
CommonsWare Avatar answered Sep 22 '22 02:09

CommonsWare