0
votes

I used the following Drive API code in Android for download files from Google Drive.

GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(GoogleDriveActivity.this);

DriveClient mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

DriveResourceClient mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);

By using this code I am able to download all files i.e Docx, Doc, Image, xls, xlsx, txt, pdf etc.

but it has given the issue for the following files.

Google Doc (application/vnd.google-apps.document),

SpreadSheet (application/vnd.google-apps.spreadsheet),

Presentation file (application/vnd.google-apps.presentation)

even I tried to change metadata for the selected file by using this code but still, its shown file size is 0 (Zero) and the extension is null.

MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setMimeType(Constants.MIME_TYPE_DOCX)
            .build();

Task<Metadata> updateMetadataTask =
            mDriveResourceClient.updateMetadata(file, changeSet);

So please suggest the solution if anybody implemented it.

1

1 Answers

0
votes

I tried to download Google Doc, Spreadsheet and Presentation file by using Google Drive Android API but didn’t get any proper solution for it by using Drive API.

But I have read in many places that you can download this documents using REST. Finally, I got the right solution for it when I combined both these codes i.e. Drive API Code and REST code

Here is the code for it.

First, you need to add these two lines in your build.gradle file in App module.

compile('com.google.api-client:google-api-client-android:1.23.0') {
   exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev107-1.23.0') {
  exclude group: 'org.apache.httpcomponents'
}

Second, Initialize GoogleAccountCredential and Drive by your selected account.

private com.google.api.services.drive.Drive driveService = null;
private GoogleAccountCredential signInCredential;
private long timeStamp;
private String fileName;


// Initialize credentials and service object.
signInCredential = GoogleAccountCredential.usingOAuth2(
   getApplicationContext(), Arrays.asList(SCOPES))
   .setBackOff(new ExponentialBackOff());


 if (!TextUtils.isEmpty(signInAccount.getAccount().name)) {  
  signInCredential.setSelectedAccountName(signInAccount.getAccount().name);
  signInCredential.setSelectedAccount(new Account(signInAccount.getAccount().name, getPackageName()));
}

if (!TextUtils.isEmpty(signInCredential.getSelectedAccountName())) {
   HttpTransport transport = AndroidHttp.newCompatibleTransport();
   JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
   driveService = new com.google.api.services.drive.Drive.Builder(transport, jsonFactory, signInCredential)
           .setApplicationName(appName)
           .build();
}

//Pass two parameters i.e fileId and mimeType which one you get when you select the file name.

public void retrieveGoogleDocContents(String fileId, String mimeType) throws IOException {
   try {        

   File storageDir =createStorageDir();

   timeStamp = System.currentTimeMillis();
//selectedFileName which one you get when you select any file from the drive, or you can use any name.
   fileName = selectedFileName + "." +getFileExtension(mimeType);

   File localFile = new File(storageDir, timeStamp + "_" + fileName);
   if (!localFile.exists()) {
       if (localFile.createNewFile())
           Log.d(TAG, fileCreated);
   }


   AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
       }

       @Override
       protected Boolean doInBackground(Void... params) {

           boolean isSuccess = false;
           OutputStream outputStream = null;

           try {
               outputStream = new FileOutputStream(localFile);

               com.google.api.services.drive.Drive.Files.Export request = driveService.files().export(fileId,getFileMimeType(mimeType));
               request.getMediaHttpDownloader().setProgressListener(new GoogleDriveActivity.CustomProgressListener());
               request.getMediaHttpDownloader().setDirectDownloadEnabled(false);
               request.executeMediaAndDownloadTo(outputStream);

               isSuccess = true;

           } catch (UserRecoverableAuthIOException e) {
               Log.d(TAG, "REQUEST_AUTHORIZATION Called");
               startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
           } catch (IOException transientEx) {
               // Network or server error, try later
               Log.e(TAG, transientEx.toString());
           } finally {
              close(outputStream);
           }

           return isSuccess;
       }

       @Override
       protected void onPostExecute(Boolean isSuccess) {
           Log.i(TAG, "Download Successfully :" + isSuccess);           
                    }

   };
   task.execute();
   } catch (IOException e){
   Log.e(TAG, e.toString()); 
   }
 }

public static void close(Closeable c) {
   if (c == null) return;
   try {
       c.close();
   } catch (IOException e) {
       log.log(Level.SEVERE, e.getMessage(), e);
   }
}


public static File createStorageDir() {
   String path = Environment.getExternalStorageDirectory() + "/" + Constants.IMAGE_DIRECTORY;
   File storageDir = new File(path);
   if (!storageDir.exists()) {
       if (storageDir.mkdir())
           Log.d(TAG, "Directory created.");
       else
           Log.d(TAG, "Directory is not created.");
   } else
       Log.d(TAG, "Directory exist.");

   return storageDir;
}

Here are file mime type and extension.

public final static String ICON_DOCX = "docx";
public final static String ICON_PPTX = "pptx";
public final static String ICON_XLSX = "xlsx";

public final static String MIME_TYPE_GOOGLE_DOC = "application/vnd.google-apps.document";
public final static String MIME_TYPE_GOOGLE_SPREADSHEET = "application/vnd.google-apps.spreadsheet";
public final static String MIME_TYPE_GOOGLE_PRESENTATION = "application/vnd.google-apps.presentation";
public final static String MIME_TYPE_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public final static String MIME_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public final static String MIME_TYPE_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";


public static String getFileExtension(String fileMimeType) {
   String fileExtension = Constants.ICON_PDF;

   if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
       fileExtension = Constants.ICON_DOCX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
       fileExtension = Constants.ICON_XLSX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
       fileExtension = Constants.ICON_PPTX;

   return fileExtension;
}

public static String getFileMimeType(String fileMimeType) {
   String newMimeType = Constants.MIME_TYPE_PDF;

   if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
       newMimeType = Constants.MIME_TYPE_DOCX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
       newMimeType = Constants.MIME_TYPE_XLSX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
       newMimeType = Constants.MIME_TYPE_PPTX;

   return newMimeType;
}