KVISH
KVISH

Reputation: 13178

Google Drive import Google Docs

I have the following code for getting DriveContents of a file in Google Drive. I'm able to import and get DriveContents of MS Word, text files, etc but when the file is native to Google (Google Doc, Google Sheets, etc.) i'm not able to get the contents. My code is below:

selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
    public void onResult(DriveApi.DriveContentsResult result) {
        try {
            if (!result.getStatus().isSuccess()) {
                // display an error saying file can't be opened
                Log.e(TAG, "Could not get file contents");
                return;
            }

            // DriveContents object contains pointers
            // to the actual byte stream
            DriveContents contents = result.getDriveContents();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            String contentsAsString = builder.toString();

            contents.discard(getGoogleApiClient());

            Log.i(TAG, contentsAsString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

Whenever I get a Google format file, it simply returns a result that is not a success and shows the error in my logs. How can I get the file contents of those files as well? Is there something special i'm supposed to do?

I'm reading the following documentation:

https://developers.google.com/drive/android/files

Upvotes: 2

Views: 148

Answers (1)

KVISH
KVISH

Reputation: 13178

Not sure if this is the best solution but I did it the following way. I check in the metadata if it's a Google format (doc, sheets, etc) and if it is, I have an AsyncTask that does the below:

// accountName is the email address the user used when choosing which account
String scope = "oauth2:https://www.googleapis.com/auth/drive.file";
token = GoogleAuthUtil.getTokenWithNotification(fragment.getActivity(), accountName, scope, null);

After doing the above, you can get the file using the API:

https://developers.google.com/drive/web/manage-downloads

The token from the above gives the Authentication header token on the downloading. We can export the file as docx, pdf, etc and download it that way.

Upvotes: 2

Related Questions