Google Drive Android API - Check if folder exists

Jakob picture Jakob · Feb 11, 2014 · Viewed 10.4k times · Source

I'm trying to figure out how to check if a folder exists in Google Drive using the new Google Drive Android API

I've tried the following, thinking that it would either crash or return null if the folder is not found, but it doesn't do that (just as long as it is a valid DriveId, even though the folder has been deleted).

DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), driveId));

If i try to create a file the folder I get from the above code, it does not crash either? I'm clearly having a little hard time understanding how this new API works all to together, especially with the very limited tutorials and SO questions out there, and I'm really stuck on this one, so any input will be much appreciated.

Just to clarify my problem: I'm creating a file in a specified Google Drive folder, but if the folder does not exist (has been deleted by user), I want to create it first.

Answer

Jakob picture Jakob · Mar 19, 2014

After a lot of research this is the code I ended up with. It works properly, but has an issue: When a folder is trashed in Google Drive it takes some time (hours) before the metadata I can fetch from my app is updated, meaning that this code can first detect if the folder has been trashed a couple of hours later the trashing event actually happened - further information and discussions can be found here.

public class checkFolderActivity extends BaseDemoActivity {

    @Override
    public void onConnected(Bundle connectionHint) {
        super.onConnected(connectionHint);

        DriveId folderId = DriveId.decodeFromString(folderId);
        DriveFolder folder = Drive.DriveApi.getFolder(mGoogleApiClient, folderId);
        folder.getMetadata(mGoogleApiClient).setResultCallback(metadataRetrievedCallback);

    }

     final private ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new
        ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {
                    Log.v(TAG, "Problem while trying to fetch metadata.");
                    return;
                }

                Metadata metadata = result.getMetadata();
                if(metadata.isTrashed()){
                    Log.v(TAG, "Folder is trashed");
                }else{
                    Log.v(TAG, "Folder is not trashed"); 
                }

            }
        };
}