4

I have spend more then one day but not getting any working solution which provide me uploading / downloading files to Google Drive.

I have tried Google Play Service but i didn't find any method which upload / download files.

I try Google Client libraries but there are some method are not resolved.

such as :

service.files().insert(body, mediaContent).execute();
errors: The method execute() is undefined for the type Drive.Files.Insert

I can upload image through below code but this is Google Drive file up loader. I can only upload one only one file at a time.

mFile = new java.io.File(fileList.get(i));
                Log.i(TAG, "Creating new contents.");
                Drive.DriveApi.newContents(mGoogleApiClient).addResultCallback(
                        new OnNewContentsCallback() {

                            @Override
                            public void onNewContents(ContentsResult result) {

                                if (!result.getStatus().isSuccess()) {
                                    Log.i(TAG, "Failed to create new contents.");
                                    return;
                                }

                                Log.i(TAG, "New contents created.");

                                OutputStream outputStream = result
                                        .getContents().getOutputStream();

                                byte[] byteStream = new byte[(int) mFile
                                        .length()];
                                try {
                                    outputStream.write(byteStream);
                                } catch (IOException e1) {
                                    Log.i(TAG, "Unable to write file contents.");
                                }

                                MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                        .setMimeType("image/jpeg")
                                        .setMimeType("text/html")
                                        .setTitle("Android Photo.png").build();
                                // Create an intent for the file chooser, and
                                // start it.
                                IntentSender intentSender = Drive.DriveApi
                                        .newCreateFileActivityBuilder()
                                        .setInitialMetadata(metadataChangeSet)
                                        .setInitialContents(
                                                result.getContents())
                                        .build(mGoogleApiClient);
                                try {
                                    mActivity.startIntentSenderForResult(
                                            intentSender, REQUEST_CODE_CREATOR,
                                            null, 0, 0, 0);
                                    publishProgress(1);
                                } catch (SendIntentException e) {
                                    Log.i(TAG, "Failed to launch file chooser.");
                                    publishProgress(0);
                                }
                            }
                        });

But still fighting for downloading a file.

ParikshitSinghTomar
  • 417
  • 1
  • 4
  • 28
  • 1
    refer this link http://stackoverflow.com/questions/16964218/android-launch-a-google-drive-application-from-another-application-not-uploaded – Praveena Feb 05 '14 at 06:26
  • 1
    Hi M D, this not about code. Actually the problem is I should use Google Play Service or Google Provided Client libraries. If I use libraries then we can not use Google Play Service because some file are crossed such as Drive class. which is in both library and Google Play Services. If I am using Google Play Service than don't know about any upload of download method. – ParikshitSinghTomar Feb 05 '14 at 06:31
  • thanks @Praveen, but what happen if drive app is not installed. I am merging Google Drive in my app. Actually I am merging Dropbox, Google Drive, SkyDrive, Amazon etc. – ParikshitSinghTomar Feb 05 '14 at 06:35
  • @MD, I think we should not use both library Google Play Services and Google Client Library at a time or we should? – ParikshitSinghTomar Feb 05 '14 at 06:40
  • @PKTomar u r absolutely right. I faced this same issue – M D Feb 05 '14 at 06:42
  • @PKTomar yes u r right. – M D Feb 05 '14 at 06:47
  • Check the question here: http://stackoverflow.com/q/15675689/1739882 – Chintan Soni Feb 05 '14 at 07:37
  • Thats ok, i figured it out. Also we are using Drive API v3 which I dont think was released back in Feb. Anyway I think we have a consensus that Google docs glimpse over implementation details and generally suck. – toidiu Dec 19 '14 at 05:37
  • The code above is missing the write to the write of the picture file bytes, it should look like this: byte[] byteStream = new byte[(int) picFile.length()]; FileInputStream fileInputStream = new FileInputStream(picFile); fileInputStream.read(byteStream); fileInputStream.close(); – Eli Mar 22 '16 at 13:53
  • refer this link https://stackoverflow.com/a/49297056/1201441, there describe upload file in google drive. you can upload any type of file just change file_path and respected Mime type – TejaDroid Mar 15 '18 at 10:54

4 Answers4

3

I got the solution. We should never use Android API for complete Drive access. We should work on pure java code as Google also said that to access Drive for broad access use java libraries.

I remove all the code related to Google play services. I am now using completely using java and easily upload, delete, edit, download all whatever I want.

One more thing Google doc doesn't provide a detail description about Google Drive in respective to android api while when work on java libraries you can get already created methods and more.

I am not giving any code but saying that for me or for others who interested in Drive complete access use Java based codes.

peterh
  • 11,875
  • 18
  • 85
  • 108
ParikshitSinghTomar
  • 417
  • 1
  • 4
  • 28
  • Sorry bro right now I have not any code snippet actually that was my company project and I switch my job. But basically at that time google drive android api doesn't work well and I done lots of google and finally I found some java libraries(client libraries) and then I worked on add,delete,upload files and folders also. – ParikshitSinghTomar Dec 18 '14 at 04:54
  • Hi @PKTomar could you help me as i also have faced many problems regarding google drive downloading files. i used "google play service" for google drive file downloading. Could you tell me or give any link about the details instruction you followed? – ImonBayazid May 31 '15 at 06:04
0

Upload File to Google Drive

Drive.Files.Insert insert;
try {
    final java.io.File uploadFile = new java.io.File(filePath);
    File fileMetadata = new File();
    ParentReference newParent = new ParentReference();
    newParent.setId(upload_folder_ID);
    fileMetadata.setParents(
            Arrays.asList(newParent));
    fileMetadata.setTitle(fileName);
    InputStreamContent mediaContent = new InputStreamContent(MIMEType, new BufferedInputStream(
                new FileInputStream(uploadFile) {
                    @Override
                    public int read(byte[] buffer,
                            int byteOffset, int byteCount)
                            throws IOException {
                        // TODO Auto-generated method stub
                        Log.i("chauster","progress = "+byteCount);
                        return super.read(buffer, byteOffset, byteCount);
                    }
                }));
            mediaContent.setLength(uploadFile.length());
    insert = service.files().insert(fileMetadata, mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    FileUploadProgressListener listener = new FileUploadProgressListener();
    uploader.setProgressListener(listener);
    uploader.setDirectUploadEnabled(true);
    insert.execute();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

public class FileUploadProgressListener implements MediaHttpUploaderProgressListener {

    @SuppressWarnings("incomplete-switch")
    @Override
    public void progressChanged(MediaHttpUploader uploader) throws IOException {
        switch (uploader.getUploadState()) {
            case INITIATION_STARTED:
                break;
            case INITIATION_COMPLETE:
                break;
            case MEDIA_IN_PROGRESS:
                break;
            case MEDIA_COMPLETE:
                break;
        }
    }
}

and Download file from google drive look this

Community
  • 1
  • 1
henry4343
  • 3,871
  • 5
  • 22
  • 30
0

Google SDK is now android friendly. There is a full-access scope which gives you access to listing and reading all the drive files and which can be used in Android apps easily since our newer client library is Android-friendly! I also recommend watching this talk from Google IO which is explains how to integrate mobile apps with Drive

The library makes authentication easier

 /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
        .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  } 

The library runs on Google App Engine

Media Upload

class CustomProgressListener implements MediaHttpUploaderProgressListener {
  public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
      case INITIATION_STARTED:
        System.out.println("Initiation has started!");
        break;
      case INITIATION_COMPLETE:
        System.out.println("Initiation is complete!");
        break;
      case MEDIA_IN_PROGRESS:
        System.out.println(uploader.getProgress());
        break;
      case MEDIA_COMPLETE:
        System.out.println("Upload is complete!");
    }
  }
}

File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();

You can also use the resumable media upload feature without the service-specific generated libraries. Here is an example:

File mediaFile = new File("/tmp/Test.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);
uploader.setProgressListener(new CustomProgressListener());
HttpResponse response = uploader.upload(requestUrl);
if (!response.isSuccessStatusCode()) {
  throw GoogleJsonResponseException(jsonFactory, response);
}
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
-1

I also tried this, I was searching for tutorials to upload some user data to their own account. But I did not found anything. Google suggests google firebase storage instead of google drive. If you think, how WhatsApp uses google drive to upload data. Then my answer is that google provides special service to WhatsApp. So use firebase storage, it is easy and very cheap and also updated. Use documentation to use them very properly. The docs are really awesome.

Vijay
  • 1,163
  • 8
  • 22