我目前正在研究在Android设备与Google云端硬盘之间同步数据的方法,偶然发现https://github.com/googledrive/android-quickeditor上的示例代码,但在打开现有文件然后点击“保存”时遇到问题变化'。基本上有问题的代码在这里:
@Override
protected com.google.android.gms.common.api.Status doInBackground(DriveId... params) {
R await;
DriveFile file = params[0].asDriveFile();
PendingResult<DriveContentsResult> openDriveContentsResult = file.open(mClient, DriveFile.MODE_WRITE_ONLY, null);
if (!openDriveContentsResult.await().getStatus().isSuccess()) {
return openDriveContentsResult.await().getStatus();
}
Changes changes = edit(openDriveContentsResult.await().getDriveContents());
PendingResult<MetadataResult> metadataResult = null;
PendingResult<com.google.android.gms.common.api.Status> closeContentsResult = null;
if (changes.getMetadataChangeSet() != null) {
metadataResult = file.updateMetadata(mClient, changes.getMetadataChangeSet());
if (!metadataResult.await().getStatus().isSuccess()) {
return metadataResult.await().getStatus();
}
}
if (changes.getDriveContents() != null) {
closeContentsResult = changes.getDriveContents().commit(mClient, null);
closeContentsResult.await();
}
return closeContentsResult.await().getStatus();
}
抛出错误的确切行是:
Changes changes = edit(openDriveContentsResult.await().getDriveContents());
错误为java.lang.IllegalStateException: Result has already been consumed
。我引用了PendingResult类引用,它清楚地指出“在使用await()
检索结果或传递给结果回调之后,尝试再次检索结果是错误的。”我觉得很公平。
问题是,我该如何妥善解决这个问题?我已经注释掉了
if (!metadataResult.await().getStatus().isSuccess()) {...}
现在要避免两次调用await()
(为了调试),但是(正如预期的那样)会导致同样的错误
return closeContentsResult.await().getStatus();
那么......我该如何解决这个问题?好吗?
答案 0 :(得分:0)
解决。对于那些对此感到沮丧的人:
@Override
protected com.google.android.gms.common.api.Status doInBackground(DriveId... params)
{
R await;
DriveFile file;
Changes changes;
PendingResult<DriveContentsResult> openDriveContentsResult;
DriveContentsResult driveContentsResult;
PendingResult<MetadataResult> updateMetadataResult;
MetadataResult metaDataResult;
PendingResult<com.google.android.gms.common.api.Status> commitResults;
com.google.android.gms.common.api.Status closeContentResults = null;
file = params[0].asDriveFile();
openDriveContentsResult = file.open(mClient, DriveFile.MODE_WRITE_ONLY, null);
driveContentsResult = openDriveContentsResult.await();
if (!driveContentsResult.getStatus().isSuccess())
{
return driveContentsResult.getStatus();
}
changes = edit(driveContentsResult.getDriveContents());
updateMetadataResult = null;
commitResults = null;
if (changes.getMetadataChangeSet() != null)
{
updateMetadataResult = file.updateMetadata(mClient, changes.getMetadataChangeSet());
metaDataResult = updateMetadataResult.await();
if (!metaDataResult.getStatus().isSuccess())
{
return metaDataResult.getStatus();
}
}
if (changes.getDriveContents() != null)
{
commitResults = changes.getDriveContents().commit(mClient, null);
closeContentResults = commitResults.await();
}
if (null == commitResults)
{
return commitResults.await().getStatus();
}
else
{
return closeContentResults.getStatus();
}
}