I'm trying to load an email attachment in my application. I can get the content, but I cannot get the file name.
Here's how my intent filter looks like:
<intent-filter>
<action
android:name="android.intent.action.VIEW" />
<category
android:name="android.intent.category.DEFAULT" />
<data
android:mimeType="image/jpeg" />
</intent-filter>
Here is what I get:
INFO/ActivityManager(97): Starting: Intent { act=android.intent.action.VIEW dat=content://gmail-ls/messages/john.doe%40gmail.com/42/attachments/0.1/SIMPLE/false typ=image/jpeg flg=0x3880001 cmp=com.myapp/.ui.email.EmailDocumentActivityJpeg } from pid 97
In my activity I get the Uri and use it to get the input stream for the file content:
InputStream is = context.getContentResolver().openInputStream(uri);
Where can I find the file name in this scenario?
Here's a "combo solution". Note the final fallback using the mimeType. You will need to define the toExtension() method...
Thank you everyone, i solved the problem. But i want to point out an error above. I guess the mobile phone you test is HTC. I use the code above run correctly on my HTC mobile phone, but when i run it on Lenovo mobile phone or M9(A mobile phone from China) i can not get the name of the email file. When id debug the code the variable "nameIndex" return "-1" not the correct number "0", so i can not get the name of the email file. Looking for an afternoon, and finally solve the problem.
}
The constant
MediaStore.MediaColumns.DISPLAY_NAME
resolves to the string"_display_name"
. The array you put in with this string is used to select the columns you want to get with the query. The behavior ofnull
for this parameter might be different for the various phones? Returning all columns (as it should according to the javadoc) by HTC phones and none for others? The javadoc states you should retrieve specific columns for performance reasons. By returning nothing on thenull
argument, the manufacturers might want to enforce this performance 'optimization'.This should therefore work on all phones:
I cannot test this, because I only have a HTC phone :).
I had the same problem to solve today and ended up finding the solution in another post : Android get attached filename from gmail app The main idea is that the URI you get can be used both for retrieving the file content and for querying to get more info. I made a quick utility function to retrieve the name :
You can use it this way in your activity :
That worked for me (retrieving the name of PDF files).