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

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.

219 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. 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!

  19. 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.

  20. 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!…

  21. 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!!

  22. 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.

  23. 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.

  24. 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?

  25. 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.

  26. 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.

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

  28. 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.

  29. 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.

  30. 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.

  31. 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.

  32. 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 🙂

  33. 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!

  34. 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!

  35. 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.

  36. 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.

  37. 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!

  38. 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.

  39. 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

  40. Great remarkable things here. I?¦m very happy to see your article. Thanks a lot and i’m taking a look forward to touch you. Will you please drop me a e-mail?

  41. Thanks for the concepts you talk about through this blog. In addition, quite a few young women which become pregnant will not even seek to get health insurance coverage because they worry they probably would not qualify. Although many states now require that insurers produce coverage in spite of the pre-existing conditions. Premiums on all these guaranteed programs are usually higher, but when considering the high cost of medical care it may be some sort of a safer strategy to use to protect a person’s financial future.

  42. Hey there just wanted to give you a quick heads up. The words in your content seem to be running off the screen in Safari. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the problem solved soon. Many thanks

  43. An excellent read that will keep readers – particularly me – coming back for more! Also, I’d genuinely appreciate if you check my website Article City about SEO. Thank you and best of luck!

  44. A powerful share, I just given this onto a colleague who was doing a bit analysis on this. And he in actual fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love reading extra on this topic. If possible, as you develop into expertise, would you thoughts updating your blog with more details? It’s extremely helpful for me. Massive thumb up for this blog submit!

  45. Thanks for making me to get new concepts about personal computers. I also have belief that one of the best ways to maintain your notebook computer in prime condition is to use a hard plastic material case, or shell, that matches over the top of your computer. These kind of protective gear are usually model distinct since they are manufactured to fit perfectly over the natural covering. You can buy these directly from the vendor, or via third party places if they are designed for your notebook, however not all laptop could have a covering on the market. Yet again, thanks for your tips.

  46. Thanks for your post right here. One thing I would really like to say is always that most professional job areas consider the Bachelors Degree as the entry level requirement for an online education. Although Associate Degrees are a great way to get started, completing ones Bachelors opens many entrances to various employment opportunities, there are numerous on-line Bachelor Course Programs available via institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions provide Online variations of their college diplomas but commonly for a greatly higher amount of money than the corporations that specialize in online college diploma programs.

  47. By my observation, shopping for consumer electronics online can for sure be expensive, yet there are some how-to’s that you can use to obtain the best things. There are always ways to obtain discount offers that could help make one to hold the best consumer electronics products at the cheapest prices. Great blog post.

  48. Pretty nice post. I just stumbled upon your blog and wanted to say that I have truly enjoyed browsing your blog posts. After all I will be subscribing to your rss feed and I hope you write again soon!

  49. I have observed that over the course of developing a relationship with real estate homeowners, you’ll be able to come to understand that, in most real estate purchase, a commission amount is paid. Finally, FSBO sellers will not “save” the payment. Rather, they try to earn the commission by means of doing a agent’s job. In doing this, they devote their money and also time to complete, as best they might, the obligations of an real estate agent. Those tasks include getting known the home by means of marketing, showing the home to willing buyers, developing a sense of buyer emergency in order to induce an offer, organizing home inspections, taking on qualification assessments with the financial institution, supervising fixes, and aiding the closing of the deal.

  50. I have been browsing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. Personally, if all webmasters and bloggers made good content as you did, the net will be much more useful than ever before.

  51. naturally like your web site however you need to check the spelling on several of your posts. Several of them are rife with spelling problems and I find it very troublesome to inform the reality then again I?¦ll certainly come back again.

  52. Thanks for the sensible critique. Me & my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more clear from this post. I am very glad to see such excellent information being shared freely out there.

  53. Great post. I was checking continuously this weblog and I’m impressed! Very useful info specially the final part 🙂 I care for such info much. I was seeking this particular information for a very long time. Thank you and good luck.

  54. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield this hike.

  55. This blog is definitely rather handy since I’m at the moment creating an internet floral website – although I am only starting out therefore it’s really fairly small, nothing like this site. Can link to a few of the posts here as they are quite. Thanks much. Zoey Olsen

  56. I’ve been absent for a while, but now I remember why I used to love this web site. Thank you, I will try and check back more frequently. How frequently you update your website?

  57. F*ckin? awesome things here. I?m very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you please drop me a mail?

  58. You actually make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand. It seems too complicated and extremely broad for me. I am looking forward for your next post, I?ll try to get the hang of it!

  59. With every little thing that appears to be building throughout this particular subject material, all your points of view are actually quite exciting. Nevertheless, I beg your pardon, but I do not subscribe to your whole strategy, all be it refreshing none the less. It looks to everyone that your comments are actually not completely justified and in reality you are yourself not even wholly certain of your point. In any event I did take pleasure in reading it.

  60. Howdy! This is my first comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading through your articles. Can you recommend any other blogs/websites/forums that cover the same subjects? Thanks!

  61. Thanks for your post on this website. From my experience, occasionally softening upward a photograph may well provide the photography with a little bit of an inventive flare. Often however, that soft clouds isn’t what precisely you had at heart and can sometimes spoil an otherwise good snapshot, especially if you intend on enlarging that.

  62. Hello there I am so delighted I found your webpage, I really found you by accident, while I was searching on Askjeeve for something else, Anyways I am here now and would just like to say thanks for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to read it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent job.

  63. Does your blog have a contact page? I’m having trouble locating it but, I’d like to shoot you an email. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it grow over time.

  64. I am curious to find out what blog platform you’re using? I’m experiencing some small security problems with my latest site and I’d like to find something more safeguarded. Do you have any solutions?

  65. I was recommended this website by my cousin I am not sure whether this post is written by him as nobody else know such detailed about my difficulty You are wonderful Thanks

  66. I have really noticed that credit improvement activity must be conducted with techniques. If not, you may find yourself damaging your positioning. In order to reach your goals in fixing your credit rating you have to verify that from this moment you pay all your monthly dues promptly prior to their planned date. It is really significant since by never accomplishing so, all other actions that you will choose to use to improve your credit positioning will not be successful. Thanks for expressing your thoughts.

  67. Many thanks for this article. I’d personally also like to state that it can often be hard when you find yourself in school and just starting out to create a long credit ranking. There are many pupils who are only trying to endure and have a long or good credit history can be a difficult element to have.

  68. I have seen that car insurance providers know the cars and trucks which are at risk of accidents along with risks. In addition they know what type of cars are inclined to higher risk and the higher risk they may have the higher the particular premium fee. Understanding the simple basics involving car insurance will allow you to choose the right style of insurance policy that could take care of the needs you have in case you become involved in an accident. Appreciate your sharing the ideas for your blog.

  69. I believe that is among the most important information for me. And i’m satisfied reading your article. However should statement on some general issues, The site style is great, the articles is in point of fact nice : D. Excellent task, cheers

  70. Superb layout and design, but most of all, concise and helpful information. Great job, site admin. Take a look at my website YK3 for some cool facts about Cosmetic Treatment.

Write A Comment

Recipe Rating