Search code examples
androidandroid-5.0-lollipop

Could not get audio file extension from ACTION_OPEN_DOCUMENT intent in Android 5.0.2


In one of my android projects I'm facing the following issue on a Samsung Tablet with Android 5.0.2: From a Fragment, the user can start to choose a file:

private static final int REQUEST_CHOOSE_FILE = 1;
...
private void chooseFile() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");

    this.startActivityForResult(intent, REQUEST_CHOOSE_FILE);
}

The activity result is handled via

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CHOOSE_FILE && resultCode == Activity.RESULT_OK && data != null) {
        Uri uri = data.getData();

        String path = Util.getPath(this.getBaseActivity().getApplicationContext(), uri);
        ...
    }
}

with Util.getPath(...) taken from Get real path from URI, Android KitKat new storage access framework

This works fine for nearly everything - but not for files taken from the "Audio" link in the left part of the filechooser. In this case I'm not able to determine the file extension with my helper function. Everything I get is the name of the file...

I'm a bit stuck, especially because the filechooser isn't showing the extension, too.

Does anyone know this issue and could give me a hint to work around it?


Solution

  • This works fine for nearly everything

    No, it does not. It works for a small subset of providers, and fewer with each passing month.

    Does anyone know this issue

    The issue is that you are relying upon intrinsically unreliable code.

    could give me a hint to work around it?

    If you want to use the content associated with a Uri, use a ContentResolver. In particular, if you want to know the MIME type of the content, use getType() on ContentResolver. From there, you can attempt to come up with a relevant file extension, such as through MimeTypeMap.