When working with Google Drive Android API (GDAA), I often need to retrieve a list of parents of a GDAA object identified by DriveId. But I could not find a direct method that would deliver the list of parents. The only way to get it is to turn the DriveId into DriveFile or DriveFolder, and subsequently apply listParents(GoogleApiClient) method.
And here, I run into a situation where the code for getting parents turns ugly, something like (it is simplified, original has try/catch logic as well):
static private GoogleApiClient mGAC;
...
ArrayList<DriveId> getParents(DriveId dId) {
ArrayList<DriveId> prnts = new ArrayList<>();
if (dId != null) {
DriveFile dFile = Drive.DriveApi.getFile(mGAC, dId);
if (dFile != null) {
MetadataBufferResult rslt = dFile.listParents(mGAC).await();
if (rslt.getStatus().isSuccess()) {
MetadataBuffer mdb = null;
try {
mdb = rslt.getMetadataBuffer();
for (Metadata md : mdb) {
if (md == null || !md.isDataValid() || md.isTrashed()) continue;
prnts.add(md.getDriveId();
}
} finally { if (mdb != null) mdb.close(); }
}
} else {
DriveFolder dFldr = Drive.DriveApi.getFolder(mGAC, dId);
if (dFldr != null) {
MetadataBufferResult rslt = dFldr.listParents(mGAC).await();
if (rslt.getStatus().isSuccess()) {
MetadataBuffer mdb = null;
try {
mdb = rslt.getMetadataBuffer();
for (Metadata md : mdb) {
if (md == null || !md.isDataValid() || md.isTrashed()) continue;
prnts.add(md.getDriveId();
}
} finally { if (mdb != null) mdb.close(); }
}
}
}
}
return prnts;
}
resume:
So it boils down to 2 questions:
I am happy to report that with evolution of the GDAA, a method
DriveId.getResourceType()
has been introduced, allowing to retrieve the type of the Drive object directly. Here is an example of code the does that:
/**
* FOLDER type object inquiry
* @param driveId Drive ID
* @return TRUE if FOLDER, FALSE otherwise
*/
static boolean isFolder(DriveId driveId) {
return driveId != null && driveId.getResourceType() == DriveId.RESOURCE_TYPE_FOLDER;
}
/**
* FILE type object inquiry
* @param driveId Drive ID
* @return TRUE if FILE, FALSE otherwise
*/
static boolean isFile(DriveId driveId) {
return driveId != null && driveId.getResourceType() == DriveId.RESOURCE_TYPE_FILE;
}