'Retrieving top level files in shared with me from google drive v3 java api

I want to query only the top level files from a google drive using java api (v3). (By top level, I mean I don't want to go recursively into folders)

I checked this question, but it does not seems to have a proper solution(even though it has a accepted solution).

I have tried couple of things :

1) I tried setting the Query

 // this gives the shared files, but gives all files, not just the top files
 Files.List request = drive.files().list().setQ("sharedWithMe = true");

2) I read somewhere that top level files in shared with me does not have any parent, So I tried to get files which does not have any parent

Similar to 'root' in parents for My Drive files, I tried couple of queries :

  drive.files().list().setQ("sharedWithMe = true and null in parents");

  drive.files().list().setQ("sharedWithMe = true and parents = null");

but they does not seem to work.

3) I tried getting all the files and then tried to select files only which has does not have parent.

   Files.List request = drive.files().list()
    .setQ("sharedWithMe = true)
    .setFields("nextPageToken, files(id, name, parents)");

even after including parents in output fields, File.getParents() gives NULL(even for files which have parent).

Question :

Is there a way we can get parents information for each file with Files.list()?

Is there a way to get files at top level of shared with me folder?(by adding some query along with sharedWithMe = true)



Solution 1:[1]

I could get the list of only the root level files shared with me, using the following code in Google Drive API V3.

First get both the files and folders of shared with me using the below code

FileList sharedWithMeResult = drive.files().list().setQ("sharedWithMe=true").execute();

To filter out the folders, you can do

List<com.google.api.services.drive.model.File> sharedWithMeFiles = sharedWithMeResult.getFiles();

for (com.google.api.services.drive.model.File file : sharedWithMeFiles) 
{
    if(file.getMimeType().contains("vnd.google-apps.folder"))
        continue;
    else
       System.out.println("Shared File Name = " + file.getName());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajesh Kumar