Tips

Unable to locate specific folders using Google Drive API

Pinterest LinkedIn Tumblr

I’m trying to get the URL of a file that is on my drive, knowing its name and the name of the parent folder. But the result is always null.

I’m using a service account with owner permission, I already put the correct credentials inside the project and shared the folder and file with the service account email, and still, the problem continues. When debugging the code it is possible to see that the size of List<File> folders = result.getFiles();  is 0.

Here is the complete code:

import android.content.Context;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class DriveAccessRunnable implements Runnable {

   private static final String APPLICATION_NAME = "School Grade";

   private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();

   private static Drive driveService;
   private final Context context;
   private final String parentFolderTitle;
   private final String fileName;
   private final DriveAccessCallback callback;

   public DriveAccessRunnable(Context context, String parentFolderTitle, String fileName, DriveAccessCallback callback) {
      this.context = context;
      this.parentFolderTitle = parentFolderTitle;
      this.fileName = fileName;
      this.callback = callback;
   }

   @Override
   public void run() {
      try {
         // Google Drive access code
         HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
         driveService = new Drive.Builder(httpTransport, JSON_FACTORY, getHttpRequestInitializer())
                 .setApplicationName(APPLICATION_NAME)
                 .build();

         // Get the URL of the file or null if not found
         String fileUrl = getFileUrl(parentFolderTitle, fileName);

        
         // Call the callback with the result
         callback.onFileUrlReceived(fileUrl);
      } catch (IOException | GeneralSecurityException e) {
         e.printStackTrace();
         // Call the callback with an error result
         callback.onError(e.getMessage());
      }

   }

   private HttpRequestInitializer getHttpRequestInitializer() throws IOException {
      InputStream credentialsStream = context.getResources().openRawResource(R.raw.credentials);

      GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream)
              .createScoped(Collections.singletonList(DriveScopes.DRIVE_FILE));

      return new HttpCredentialsAdapter(credentials);
   }

   private String getFileUrl(String parentFolderTitle, String fileName) throws IOException {
     
       // Search parent folder by title
      FileList result = driveService.files().list()
              .setQ("mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + parentFolderTitle + "'")
              .setSpaces("drive")
              .setFields("files(id)")
              .execute();

      List<File> folders = result.getFiles();

      if (!folders.isEmpty()) {
         String parentFolderId = folders.get(0).getId();

         
         // Browse files inside the parent folder
         result = driveService.files().list()
                 .setQ("'" + parentFolderId + "' in parents and trashed=false")
                 .setFields("files(name, webViewLink)")
                 .execute();

         List<File> files = result.getFiles();
         for (File file : files) {
            if (file.getName().equals(fileName)) {
               return file.getWebViewLink();
            }
         }
      }

      return null;
   }


   public interface DriveAccessCallback {
      void onFileUrlReceived(String fileUrl);
      void onError(String errorMessage);
   }
}

Vishal Swami is a hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been an interesting part for him.

95 Comments

  1. Hi, Neat post. There’s a problem with your site in web explorer, may test this?K IE nonetheless is the market chief and a huge portion of other folks will miss your fantastic writing because of this problem.

  2. I would like to show my appreciation to the writer for bailing me out of this particular trouble. After browsing through the online world and getting principles which are not pleasant, I believed my entire life was done. Being alive minus the strategies to the difficulties you’ve solved by means of your good post is a crucial case, and ones that might have negatively affected my career if I had not discovered your blog post. Your know-how and kindness in taking care of every aspect was helpful. I’m not sure what I would’ve done if I had not come across such a thing like this. I can also now relish my future. Thank you very much for your expert and results-oriented help. I will not think twice to suggest the website to anyone who desires counselling about this problem.

  3. Thanks for another informative site. Where else could I get that kind of info written in such an ideal way? I’ve a project that I am just now working on, and I have been on the look out for such info.

  4. hello!,I really like your writing very a lot! share we keep in touch more about your article on AOL? I require an expert on this space to solve my problem. Maybe that is you! Taking a look forward to see you.

  5. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how could we communicate?

  6. Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  7. Wonderful web site. A lot of useful info here. I’m sending it to a few friends ans also sharing in delicious. And naturally, thanks for your effort!

  8. I really appreciate this post. I’ve been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thx again

  9. I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

  10. Its like you learn my mind! You appear to grasp so much about this, such as you wrote the book in it or something. I believe that you simply can do with some p.c. to pressure the message house a little bit, however instead of that, this is wonderful blog. A fantastic read. I’ll definitely be back.

  11. This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article.

  12. I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to construct my own blog and would like to find out where u got this from. thank you

  13. There is noticeably a bundle to learn about this. I assume you made sure nice factors in options also.

  14. I’ll right away clutch your rss feed as I can’t find your e-mail subscription link or e-newsletter service. Do you’ve any? Please allow me recognize in order that I may subscribe. Thanks.

  15. Good ?V I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your client to communicate. Nice task..

  16. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your blog? My website is in the very same niche as yours and my users would really benefit from a lot of the information you present here. Please let me know if this ok with you. Appreciate it!

  17. I really appreciate this post. I¦ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again

  18. Lottery Defeater Software is a cutting-edge application designed to analyze and optimize your chances of winning various lottery games.

  19. I like the helpful information you provide to your articles. I’ll bookmark your blog and take a look at again here regularly. I’m somewhat sure I will be informed many new stuff proper here! Best of luck for the following!

  20. Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire actually enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access consistently rapidly.

  21. I discovered your weblog site on google and examine just a few of your early posts. Continue to maintain up the very good operate. I just extra up your RSS feed to my MSN News Reader. Searching for ahead to reading more from you in a while!…

  22. Hi, i think that i saw you visited my web site thus i came to “return the favor”.I am attempting to find things to improve my site!I suppose its ok to use some of your ideas!!

  23. Thanks for the new things you have discovered in your text. One thing I’d like to discuss is that FSBO interactions are built after a while. By releasing yourself to the owners the first end of the week their FSBO can be announced, prior to masses get started calling on Wednesday, you develop a good interconnection. By sending them instruments, educational components, free accounts, and forms, you become a strong ally. By taking a personal desire for them and their circumstances, you create a solid relationship that, on most occasions, pays off once the owners decide to go with an adviser they know along with trust – preferably you actually.

  24. It’s really a great and useful piece of information. I’m glad that you shared this useful info with us. Please keep us up to date like this. Thank you for sharing.

  25. Good day! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  26. We are a bunch of volunteers and opening a brand new scheme in our community. Your website provided us with helpful information to paintings on. You have performed an impressive task and our entire community will be thankful to you.

  27. I like this post, enjoyed this one regards for putting up. “What is a thousand years Time is short for one who thinks, endless for one who yearns.” by Alain.

  28. Very interesting subject, appreciate it for posting. “Welcome to President Bush, Mrs. Bush, and my fellow astronauts.” by Dan Quayle.

  29. I used to be very pleased to find this net-site.I wanted to thanks for your time for this excellent read!! I undoubtedly enjoying every little bit of it and I’ve you bookmarked to take a look at new stuff you weblog post.

  30. What does the Lottery Defeater Software offer? The Lottery Defeater Software is a unique predictive tool crafted to empower individuals seeking to boost their chances of winning the lottery.

  31. FitSpresso: What Is It? FitSpresso is a natural weight loss aid designed for individuals dealing with stubborn weight gain. It is made using only science-backed natural ingredients.

  32. Can I just say what a relief to seek out somebody who truly is aware of what theyre talking about on the internet. You undoubtedly know learn how to convey a problem to light and make it important. More folks need to learn this and understand this side of the story. I cant believe youre not more fashionable because you positively have the gift.

  33. Awsome info and straight to the point. I don’t know if this is truly the best place to ask but do you people have any thoughts on where to get some professional writers? Thanks 🙂

  34. Hello, you used to write excellent, but the last few posts have been kinda boring?K I miss your great writings. Past few posts are just a little out of track! come on!

  35. Hey there! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a extraordinary job!

  36. Hello There. I found your blog the use of msn. This is a very smartly written article. I will make sure to bookmark it and come back to read extra of your helpful information. Thanks for the post. I will definitely comeback.

  37. I?m now not positive the place you’re getting your info, but great topic. I must spend some time studying more or working out more. Thanks for fantastic information I was in search of this info for my mission.

  38. Someone necessarily assist to make critically posts I’d state. That is the very first time I frequented your web page and up to now? I amazed with the research you made to make this actual post extraordinary. Wonderful job!

  39. Heya i’m for the first time here. I found this board and I find It truly useful & it helped me out a lot. I’m hoping to give one thing back and help others like you helped me.

  40. I think that is one of the most significant information for me. And i’m glad studying your article. However should statement on some normal issues, The website taste is great, the articles is in point of fact great : D. Excellent process, cheers

Write A Comment