Android Google Drive API getRequest.getMediaHttpDownloader()始终为null。为什么?

时间:2013-11-16 17:59:43

标签: android google-drive-api

我正在尝试在下载驱动器文件时使用MediaHttpDownloaderProgressListener更新progressBar,但以下代码返回NullPointer异常:

  class CustomProgressListener implements MediaHttpDownloaderProgressListener {
    public void progressChanged(MediaHttpDownloader downloader) {
      switch (downloader.getDownloadState()) {
        case MEDIA_IN_PROGRESS:
          System.out.println(downloader.getProgress());
          break;
        case MEDIA_COMPLETE:
          System.out.println("Download is complete!");
      }
    }
  }

  OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/tmp/driveFile.jpg");

  DriveFiles.Get request = drive.files().get(fileId);
  request.getMediaHttpDownloader().setProgressListener(new CustomProgressListener());
  request.download(out);

异常总是在这一行:

request.getMediaHttpDownloader().setProgressListener(new CustomProgressListener());

因为“request.getMediaHttpDownloader()”为空,但是请求没问题(我测试过它)。

你能帮助我吗?

1 个答案:

答案 0 :(得分:2)

使用此代码解决:

private static void downloadFile(boolean useDirectDownload, File uploadedFile)
      throws IOException {
    // create parent directory (if necessary)
    java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
    if (!parentDir.exists() && !parentDir.mkdirs()) {
      throw new IOException("Unable to create parent directory");
    }
    OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getTitle()));

    MediaHttpDownloader downloader =
        new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
    downloader.setDirectDownloadEnabled(useDirectDownload);
    downloader.setProgressListener(new FileDownloadProgressListener());
    downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out);
  }