Search code examples
androidonactivityresult

Getting a file extension from dropbox or driver after onActivityResult()


I use this code for upload file:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        final String path = getPath(data.getData());
        final String fileExt = path.substring(path.lastIndexOf(".") + 1);
    }
}

This code work fine for select file from SDCard. But if I select file from Drive or Dropbox on line 4 I get error.

Anyone knows why it happens like that.


Solution

  • This code work fine for select file from SDCard.

    Not necessarily. After all, files do not have to have extensions. README is a valid filename, and it does not have a file extension.

    But if I select file from Drive or Dropbox on line 4 I get error

    Sure. There is no requirement for a Uri to have a file extension. For example, https://stackoverflow.com/questions/53131985/android-get-extension-file-from-dropbox-or-driver-after-onactivityresult is a Uri, and it does not have a file extension.

    If data.getData().getScheme() returns file, you are welcome to try your algorithm, but it will fail for README.

    If data.getData().getScheme() returns content, you can use getContentResolver().getType(data.getData()) to get a MIME type for the content. You can then try to use MimeTypeMap to identify a file extension, though MimeTypeMap does not handle all possible MIME types.

    Overall, you need to revise your plans, such that you do not need file extensions.