iPaulPro / aFileChooser

[DEPRECATED] Android library that provides a file explorer to let users select files on external storage.
Apache License 2.0
1.79k stars 847 forks source link

Not Working for Google Drive Uri #90

Open ghost opened 7 years ago

ghost commented 7 years ago

When user have selected file from Google drive, we cannot access original file path from that Uri. Working for Google Photos Uri. Not working when users have selected document/pdf file from Google Drive

amrutbidri commented 6 years ago

Any solution to this? or found any workaround on it?

ghost commented 6 years ago

I couldn't found any. May be we need to manage by drive sdks.

I restricted user to choose from Drive though.

kk121 commented 6 years ago

I have created a pull request(#97) for this issue. Till then you can use codes in last 3 commits of this forked library: https://github.com/kk121/aFileChooser

lorenzos commented 6 years ago

I found a workaround for when file is not "local" (i.e. when FileUtils.getFile and FileUtils.getPath return null or FileUtils.isLocal is false), which is applicable for file selection from Drive #90, Google Photos #98, etc. The trick is to use a file descriptor instead of direct access, for example using something like this inside the usual onActivityResult():

try {

    final Uri uri = data.getData();
    final FileInputStream fileInputStream;
    final File file = FileUtils.getFile(this, uri);

    // Local file
    if (file != null) {
        fileInputStream = new FileInputStream(file);

    // Access to remote file (Google Photos, Drive, ...)
    } else {
        final ParcelFileDescriptor fileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
        if (fileDescriptor != null) {
            fileInputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
        } else {
            throw new IOException("Cannot open file descriptor from URI");
        }
    }

    // The following is just an example to test that the file is in fact readable
    final byte[] buffer = new byte[50];
    fileInputStream.read(buffer);
    fileInputStream.close();
    Toast.makeText(this, "Read: " + new String(buffer), Toast.LENGTH_LONG).show();

} catch (IOException e) {
    Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
    e.printStackTrace();
}