0

i have the following code

which is supposed to upload an image from my android device to my google Drive.

  private void saveFileToDrive() {

      progressDialog = ProgressDialog.show(this, "", "Loading...");

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          // File's binary content
          java.io.File fileContent = new java.io.File(fileUri.getPath());
          FileContent mediaContent = new FileContent("image/jpeg", fileContent);

          // File's metadata.
          File body = new File();
          body.setTitle(fileContent.getName());
          body.setMimeType("image/jpeg");

          File file = service.files().insert(body, mediaContent).execute();
          if (file != null) {
            showToast("Photo uploaded: " + file.getTitle());

            progressDialog.dismiss();
            //startCameraIntent();
          }
        } catch (UserRecoverableAuthIOException e) {
          startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });
    t.start();
  }

The thing is the upload never ends. That's weird as the image not too big

and I guess if I would have upload it via original Drive App, it would be done faster.

1) how can I show the upload progress?

2) how can I make a callback within the same Activity after the upload is done?

Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

2 Answers2

2

Downloading file from Google Drive:

  1. You can either use an AsyncTask in which you can obtain an inputstream from the url and write a while loop for reading each line and showing the downloaded data on a dialog as below.

    @Override
    protected Boolean doInBackground(FilesObject... files) {
    // getting an input Stream.
    HttpResponse resp = service.getRequestFactory()
            .buildGetRequest(new GenericUrl(file.SourceImageUrl)).execute();
    fileSize = resp.getHeaders().getContentLength();
    if (fileSize != -1) {
        fileSizeReadableString = DiskSpaceUtil.readableFileSize(fileSize);
    }
    InputStream is = resp.getContent();
    
    // publishing the progress in a dialog.
    int completed = 0;
    while ((length = inputStream.read(buffer)) > 0) {
        if (!this.isCancelled()) {
            completed += length;
            fOutputStream.write(buffer, 0, length);
            publishProgress(completed);
        } else {
            fOutputStream.flush();
            fOutputStream.close();
            inputStream.close();
            return;
        }
    }
    
    @Override
    protected void onProgressUpdate(Integer... values) {
    
        sendShowloader("Downloading file ... \n"
                + DiskSpaceUtil.readableFileSize(number) + " of "
                + fileSizeReadableString);
    
    }
    
  2. You can use the inherent Google Drive's Download Listeners which can be set with insert object.

Uploading File to Google Drive :

We can upload files to google drive using Google own implementation of MediaHttpUploaderProgressListener as below :

    { // ... Inside some thread

    java.io.File fil = new java.io.File(file.SourceImageUrl);
    InputStream is = new FileInputStream(fil);

    InputStreamContent mediaContent = new InputStreamContent(file.mimeType, is);
            mediaContent.setLength(fil.length());

    // File's metadata.
    File body = new File();
    body.setTitle(file.FileTitle);
    body.setMimeType(file.mimeType);
    body.setParents(parents);
    body.setDescription("Content Uploaded to "+ DriveName);
    // Inserting the Remote Resource into Google Drive
    File destFile = null;

    if(fil.length() > 5 * 1024 * 1024)
    {
        // Resumable Uploads when the file size exceeds a file size of 5 MB.
        // check link : 
        // 1) https://code.google.com/p/google-api-java-client/source/browse/drive-cmdline-sample/src/main/java/com/google/api/services/samples/drive/cmdline/DriveSample.java?repo=samples&r=08555cd2a27be66dc97505e15c60853f47d84b5a
        // 2) http://stackoverflow.com/questions/15970423/uploading-downloading-of-large-size-file-to-google-drive-giving-error

        Insert insert = mService.files().insert(body, mediaContent);
        MediaHttpUploader uploader = insert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        uploader.setProgressListener(new FileUploadProgressListener());
        destFile = insert.execute();

    }   
    else
    {
        // Else we go by Non Resumable Uploads, which is safe for small uploads.
        destFile = mService.files().insert(body, mediaContent).execute();
    }

    ... }

    // Now the implementation of FileUploadProgressListener which extends MediaHttpUploaderProgressListener

public static class FileUploadProgressListener implements MediaHttpUploaderProgressListener {

    public void progressChanged(MediaHttpUploader uploader) throws IOException {
      switch (uploader.getUploadState()) {
        case INITIATION_STARTED:
          postToDialog("Initiation Started");
          break;
        case INITIATION_COMPLETE:
          postToDialog("Initiation Completed");
          break;
        case MEDIA_IN_PROGRESS:
          // postToDialog("Upload in progress");
          postToDialog("Upload percentage: " + uploader.getProgress());
          break;
        case MEDIA_COMPLETE:
          postToDialog("Upload Completed!");
          break;

        case NOT_STARTED :
            postToDialog("Not Started!");
            break;
      }
    }
  }
Sri Krishna
  • 302
  • 1
  • 2
  • 14
  • I have updated my answer, as you can see in the Resumable upload Block. the insert method's uploader is being set with not Direct Uploads, meaning they will now be inserting files to google drive using resumable uploads which are done using the code within the insert method as specified in [Uploads](https://developers.google.com/drive/manage-uploads), the whole implementation is managed within the insert api ! You can see the source code of the google client libs by using a JD plugin for Eclipse, where it is all summed up internally. :) – Sri Krishna Nov 20 '13 at 03:53
  • @SriKrishna,, Can you please provide full code showing dependencies as i am hell confused in importing and resolving the Drive file, Insert api :(. Please help – SimpleCoder Jun 07 '17 at 15:59
  • it is multipath upload? – Nathani Software Aug 29 '19 at 10:50
-2

Simply check your network connection first!!!

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 17 '22 at 09:20
  • Welcome to Stack Overflow! I do not see how this answers the question at the top of this page, but it should. Please [edit] according to [answer] or delete the answer. Otherwise it risks being flagged as "not an answer" and being deleted. – Yunnosch Jan 23 '22 at 13:57
  • Welcome to Stack Overflow! Please phrase this as an explained conditional answer, in order to avoid the impression of asking a clarification question instead of answering (for which a comment should be used instead of an answer, compare https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead ). For example like "If your problem is ... then the solution is to .... because .... ." – Yunnosch Jan 23 '22 at 13:57