I am using an Intent to let the user select a file, and after the user has done that I want to know what kind of file-type the selected file is.
The intent:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
In my onActivityResult I want to extract the path from the intent through intent.getData() and all of it's "submethods" (getScheme(), getLastPathSegment() etc). However, I only get the Uri for the selected file.
Example of Uris':
Uri: content://media/external/audio/media/15185 //This is an audiofile
Uri: content://media/external/audio/media/20 //Another audiofile
Uri: content://media/external/images/media/20577 //this is a picture
Uri: file:///storage/emulated/0/testWed%20Apr%2017%2011%3A10%3A34%20CEST%202013 //This is a file
I've seen solutions of how to get the absolute path when the user is only allowed to chose images or audios. But how do I do I get the absolutePath (the real path with the name and file-ending, e.g. MyPicture.jpeg) if I want to allow the user to select from different file types?
The code I've been twiggling with to try to get the path-name in onActivityResult(int requestCode, int resultCode
String fileName = data.getData().getLastPathSegment().toString();
System.out.println("Uri: " +data.getData().toString());
File f = new File(fileName);
System.out.println("TrYinG wIWThA Da FiLE: " +f.getAbsolutePath());
System.out.println("FileNAME!!!: "+fileName);
By file-ending I'm assuming you mean the file extension? (i.e. mp4)
If so you can use the ContentResolver
to get the mimetype:
String mimeType = getContentResolver().getType(sourceUri);
This will give you the mimetype assuming they are within the MediaStore
which they should if you have the content Uri
. so you'll get something like "image/png", "video/mp4", etc.
Then you can use MimeTypeMap
to get the file extension from the mimetype:
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
Note that you should never substring the mimetype after "/" to get the extension as some mimetype does not use its extension such as ".mov" files which has the mimetype "video/quicktime"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With