0

I am trying to access all files and folders from google drive to a arraya list. But I can get only one file from Drive. What to do get all files and folders from google drive. I am using the following code..

Thanks Arun

public void onConnected(Bundle connectionHint) {
    // Log.i(TAG, "API client connected.");
    Toast.makeText(getActivity(), "Successfully logged in", Toast.LENGTH_LONG).show();
    DriveFolder s = Drive.DriveApi.getRootFolder(mGoogleApiClient);

    String s1 = (Drive.DriveApi.getRootFolder(mGoogleApiClient)).getDriveId().toString();
    DriveId sFolderId2 = DriveId.decodeFromString(s1);
    DriveId sFolderId = (Drive.DriveApi.getRootFolder(mGoogleApiClient)).getDriveId();

    DriveFolder folder = Drive.DriveApi.getFolder(mGoogleApiClient, sFolderId);
    folder.listChildren(mGoogleApiClient).setResultCallback(rootFolderCallback);
    //  findAll(folder);

}

public ResultCallback<DriveApi.MetadataBufferResult> rootFolderCallback = new
        ResultCallback<DriveApi.MetadataBufferResult>() {
            @Override
            public void onResult(DriveApi.MetadataBufferResult result) {
                if (!result.getStatus().isSuccess()) {

                    return;
                }
                 resultarray = new ArrayList<String>();
                int hh = result.getMetadataBuffer().getCount();

                for (int i = 0; i < result.getMetadataBuffer().getCount(); i++) {
                    resultarray.add(result.getMetadataBuffer().get(i).getTitle());
                }

                Toast.makeText(getActivity(), "Successfully listed files.", Toast.LENGTH_LONG).show();

            }
        };
mikhail
  • 137
  • 2
  • 14

2 Answers2

1

UPDATE (Aug 25, 2015, 10:39 MST)

Based on your comment below, you have 2 options:

1/ Stay with the GDAA, use one of the INTENTS:
- Pick a file with opener activity
- Pick a folder with opener activity
See, GDAA does not let your app see anything it did not create (SCOPE_FILE only), but it still allows user to browse everything. If the user selects a file, it will become visible to you app. I don't know your app's intentions, so I can't say if this approach is usable.

2/ Switch to the REST with the DRIVE scope and your app will see everything (user has to approve up front). The basic CRUD implementation can be found here but make sure you change the scope in the init() method to 'DriveScopes.DRIVE'.

In case your app needs to iterate down the folder tree, collecting files in the process, both 'testTree()' and 'deleteTree()' methods in the MainActivity() do exactly that.

You may also stay with the GDAA and add REST functionality to it by adding

com.google.api.services.drive.Drive mGOOSvc = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(),
        GoogleAccountCredential.usingOAuth2(appContext, Collections.singletonList(DriveScopes.DRIVE))
        .setSelectedAccountName(email)

but you will sooner or later run into problems caused by GDAA caching / latency.

ORIGINAL ANSWER

Try this approach:

  private static GoogleApiClient mGAC;
  /****************************************************************************
   * find file/folder in GOODrive
   * @param prnId   parent ID (optional), null searches full drive, "root" searches Drive root
   * @param titl    file/folder name (optional)
   * @param mime    file/folder mime type (optional)
   * @return        arraylist of found objects
   */
  static void search(String prnId, String titl, String mime) {
    if (mGAC != null && mGAC.isConnected()) {
      // add query conditions, build query
      ArrayList<Filter> fltrs = new ArrayList<>();
      if (prnId != null){
        fltrs.add(Filters.in(SearchableField.PARENTS,
        prnId.equalsIgnoreCase("root") ?
          Drive.DriveApi.getRootFolder(mGAC).getDriveId() : DriveId.decodeFromString(prnId)));
      }
      if (titl != null) fltrs.add(Filters.eq(SearchableField.TITLE, titl));
      if (mime != null) fltrs.add(Filters.eq(SearchableField.MIME_TYPE, mime));
      Query qry = new Query.Builder().addFilter(Filters.and(fltrs)).build();

      // fire the query
      Drive.DriveApi.query(mGAC, qry).setResultCallback(new ResultCallback<MetadataBufferResult>() {
        @Override
        public void onResult(MetadataBufferResult rslt) {
          if (rslt != null && rslt.getStatus().isSuccess()) {
            MetadataBuffer mdb = null;
            try {
              mdb = rslt.getMetadataBuffer();
              if (mdb != null ) for (Metadata md : mdb) {
                if (md == null || !md.isDataValid()) continue;
                String title = md.getTitle();
                DriveId driveId = md.getDriveId();
                //.......
              }
            } finally { if (mdb != null) mdb.close(); }
          }
        }
      });
    }
  }

Call it first with NULLs

search(null,null,null)

To list all the files in your Google Drive. You will see all the files your Android App created. But only those - FILE scope does not see anything else.
If you need to scan the directory tree, you may look closer at this GDAA demo, in MainActivity, there is are 'testTree()' / 'deleteTree() methods that recursively scan the directory tree structure.

Also, you may look at the answer here, it deals with a similar issue (especially the comments exchange under the answer).

Good Luck

Community
  • 1
  • 1
seanpj
  • 6,735
  • 2
  • 33
  • 54
  • Thanks Seanpj. I need all folderes too .. created by my app and also manually created inside the google Drive too.. – mikhail Aug 25 '15 at 15:56
  • I used the above code. But Still I get Only one file one(it is a deleted one from G drive). Actually my purpose is that I need to get all folders name(no need for files) – mikhail Sep 09 '15 at 13:01
  • I you need files/folders your Android app did not create, you need to use REST Api with DRIVE scope (the link is in the answer above). – seanpj Sep 09 '15 at 19:56
  • This is useful. But I have , a folder Id. I need to get all folders inside that one(not only the app created folders but also I need manually created folders too). – mikhail Sep 10 '15 at 13:12
  • When using REST Api you first obtain ResourceId (DriveId.getResourceId()) [see also this](http://stackoverflow.com/questions/22874657/unpredictable-result-of-driveid-getresourceid-in-google-drive-android-api/31553269#31553269) and use this ResourceId in the REST call (see [testTree() method here](https://github.com/seanpjanson/RESTDemo/blob/master/app/src/main/java/com/spjanson/restdemo/MainActivity.java) – seanpj Sep 10 '15 at 17:57
0

Please note that you can use GDAA to retrieve the files and folder that you have either uploaded from the Android Device or downloaded via the drive app. This is to have more security (as quoted by Google).

In he code you need to ensure that you are trying all possible combinations for the files that may be present in your Google Drive account. For example, check if you are tracking the parent of a file or a folder. If this condition is not met your app wont be able to retrieve those specific files.

/** Get the list of parents Id in ascending order. */
   private List<String> collectParents(String folderId, Map<String, String> folderIdToParentId){
      String parentId = folderIdToParentId.get(folderId);
      if (logger.isTraceEnabled()){
         logger.trace("Direct parent of {} is {}", folderId, parentId);
      }
      List<String> ancestors = new ArrayList<String>();
      ancestors.add(parentId);

      if (folderIdToParentId.containsKey(parentId)){
         ancestors.addAll(collectParents(parentId, folderIdToParentId));
         return ancestors;
      }
      return ancestors;
   }

See the full code here.

AniV
  • 3,997
  • 1
  • 12
  • 17