How to open a file in Android via an Intent

tim.kaufner picture tim.kaufner · Sep 25, 2012 · Viewed 34.4k times · Source

how can I open a file that has been previously stored in the "privat" filesystem? The file is being downloaded by a webservice and should be stored on local fs. I got a "strange" error when trying to open the file via an Intent (Action_View). Although the file is present in the filesystem (saw the file in the file explorer in emulator/eclipse) it won't be shown in the calling galery activity that is launched. Instead of the picture the galery shows a black screen with not content in there (except the action bar). The same occurs when trying to open a pdf/movie/mp3 file via this method (pdf says for example that the file is corrupt).

BTW: The data that has been stored on the local fs is valid (not corrupt), I downloaded the files from debugger (via pull method) and the files can be opened on my workstation...

public void onAttachment(Context context, Attachment attachment) {
    try {
        //Attachment is a structured data object that contains of a byte[], filename and mimetype (like image/jpeg)
        FileOutputStream fos = FileOutputStream fos = context.openFileOutput(attachment.getAttachmentFileName(), Context.MODE_PRIVATE);
        fos.write(attachment.getBinary());
        fos.flush();
        fos.close();
        File f = context.getFileStreamPath(attachment.getAttachmentFileName());
        Uri uri = Uri.fromFile(f);          
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri,attachment.getAttachmentMimetype());
        context.startActivity(intent);                  
    } catch (IOException e) {
        e.printStackTrace();
    }
}           

Answer

Ondřej Z picture Ondřej Z · Sep 25, 2012

What is the type of the Attachment in your code? Perhaps it returns wrong mime type?

This code works for me:

File file = new File("EXAMPLE.JPG");

// Just example, you should parse file name for extension
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".JPG");

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), mime);
startActivityForResult(intent, 10);