Vijay
Vijay

Reputation: 565

Can't able get bytes from native google document from File Chooser using Intent.ACTION_GET_CONTENT

Content provider newbie here. I am trying to open a document from google drive using intent chooser below

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");   
Intent intent = Intent.createChooser(intent, "Import Document");

I can able to get bytes from files like docx, image and pdf but when trying to open native google document, I am getting FileNotFoundException with the information like the file is virtual.

Sometimes it throws PermissionDeniel exception.

I am reading bytes using the below method

activity.getContentResolver().openInputStream(contentUri)

Suggestions would be very much appreciated.

Thank you.

Upvotes: 1

Views: 66

Answers (1)

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17613

There's a Reading Files in Drive API for Android.

Opening the file contents

In order to be able to read a file, you must start by opening its DriveContents resource in DriveFile.MODE_READ_ONLY or DriveFile.MODE_READ_WRITE mode, depending on whether you prefer to work with the InputStream or ParcelFileDescriptor class.

Note: The InputStream class is only available for files opened in READ_ONLY mode. Files opened with READ_WRITE must use the ParcelFileDescriptor class to read from the file.

The DriveFile.open method retrieves the locally synced file resource and opens it. If the file is not synced with the local storage, it retrieves the file from the Drive service and returns a DriveContents resource. For example:

DriveFile file = ...
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
        .setResultCallback(contentsOpenedCallback);

A DriveContents resource contains a temporary copy of the file's binary stream which is only available to your application. If multiple applications are accessing the same file, there are no race conditions between DriveContents resources. In this situation, the last write operation will be the final state of the content.

Handling the response requires you to check if the call was successful or not. If the call was successful, you can retrieve the DriveContents resource. This resource contains methods to retrieve an InputStream or ParcelFileDescriptor to read the file's binary contents. The following example demonstrates how to retrieve a file's DriveContents:

ResultCallback<DriveContentsResult> contentsOpenedCallback =
        new ResultCallback<DriveContentsResult>() {
    @Override
    public void onResult(DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            // display an error saying file can't be opened
            return;
        }
        // DriveContents object contains pointers
        // to the actual byte stream
        DriveContents contents = result.getDriveContents();
    }
};

Upvotes: 1

Related Questions