How to delete a file on google drive using Google Drive Android API

UPDATE (April 2015)
GDAA finally has it’s own ‘trash‘ functionality rendering the answer below IRRELEVANT.

ORIGINAL ANSWER:
As Cheryl mentioned above, you can combine these two APIs.

The following code snippet, taken from here, shows how it can be done:

First, gain access to both GoogleApiClient, and …services.drive.Drive

GoogleApiClient _gac;
com.google.api.services.drive.Drive _drvSvc;

public void init(MainActivity ctx, String email){
  // build GDAA  GoogleApiClient
  _gac = new GoogleApiClient.Builder(ctx).addApi(com.google.android.gms.drive.Drive.API)
        .addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName(email)
        .addConnectionCallbacks(ctx).addOnConnectionFailedListener(ctx).build();

  // build RESTFul (DriveSDKv2) service to fall back to for DELETE
  com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential crd =
  GoogleAccountCredential
    .usingOAuth2(ctx, Arrays.asList(com.google.api.services.drive.DriveScopes.DRIVE_FILE));
  crd.setSelectedAccountName(email);
  _drvSvc = new com.google.api.services.drive.Drive.Builder(
          AndroidHttp.newCompatibleTransport(), new GsonFactory(), crd).build();
}

Second, implement RESTful API calls on GDAA’s DriveId:

public void trash(DriveId dId) {
  try {
    String fileID =  dId.getResourceId();
      if (fileID != null)
        _drvSvc.files().trash(fileID).execute();
  } catch (Exception e) {} 
}

public void delete(DriveId dId) {
  try {
    String fileID = dId.getResourceId();
      if (fileID != null)
        _drvSvc.files().delete(fileID).execute();
  } catch (Exception e) {} 
}

… and voila, you are deleting your files. And as usual, not without problems.

First, if you try to delete a file immediately after you created it, the getResourceId() falls on it’s face, returning null. Not related to the issue here, I’m gonna raise an SO nag on it.

And second, IT IS A HACK! and it should not stay in your code past GDAA implementation of TRASH and DELETE functionality.

Leave a Comment