使用Google云端硬盘Android API(GDAA)时,我经常需要检索由DriveId标识的GDAA对象的父级列表。但是我找不到能够提供父母名单的直接方法。获得它的唯一方法是将DriveId转换为DriveFile或DriveFolder,然后应用listParents(GoogleApiClient)方法。
在这里,我遇到了让父母变得丑陋的代码,例如(它是简化的,原始的还有try / catch逻辑):
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;
}
履历:
所以归结为两个问题:
答案 0 :(得分:1)
我很高兴通过GDAA的演变报告一种方法
DriveId.getResourceType()
已经引入,允许直接检索Drive对象的类型。以下是代码的示例:
/**
* 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;
}
答案 1 :(得分:0)
您是否尝试过使用以下方法:Drive.DriveApi.query(googleApiClient,query);
您必须创建适当的查询才能访问文件的父级。这个解决方案的好处是它依赖于DriveId而不是FileId或FolderId。解决方案应该类似于:
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.PARENTS, "DriveId"))
.build();
Drive.DriveApi.query(googleApiClient, query);
您可以在以下页面中详细了解此解决方案:https://developers.google.com/drive/android/queries