11

I wanted to download file from google drive. For this I have implemented in Google Drive SDk and used the following method.

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CODE_OPENER:
            if (resultCode == RESULT_OK) {
                DriveId driveId = (DriveId) data.getParcelableExtra(
                        OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);


            }
            finish();
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

I also tried using output stream but not able to save data to a file.

I have tried searching around this, but couldn't find any useful link which can guide me how to download and store file.

Amit kumar
  • 1,585
  • 2
  • 16
  • 27

1 Answers1

8

IMO, you should read some useful links below:

Then, please refer to the following snippets, of course when getting the input stream, you can save it to a file in your device instead of printing to Logcat.

public class GoogleDriveActivity extends AppCompatActivity
        implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {           
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mProgressBar.setMax(100);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)  
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (requestCode == RC_OPENER && resultCode == RESULT_OK) {
            mSelectedFileDriveId = data.getParcelableExtra(
                    OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult result) {
        // Called whenever the API client fails to connect.
        // Do something...
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {        
        // If there is a selected file, open its contents.
        if (mSelectedFileDriveId != null) {
            open();
            return;
        }

        // Let the user pick a file...
        IntentSender intentSender = Drive.DriveApi
                .newOpenFileActivityBuilder()
                .setMimeType(new String[]{"video/mp4", "image/jpeg", "text/plain"})
                .build(mGoogleApiClient);
        try {
            startIntentSenderForResult(intentSender, RC_OPENER, null, 0, 0, 0);
        } catch (IntentSender.SendIntentException e) {
            Log.e(TAG, "Unable to send intent", e);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    private void open() {        
        mProgressBar.setProgress(0);
        DriveFile.DownloadProgressListener listener = new DriveFile.DownloadProgressListener() {
            @Override
            public void onProgress(long bytesDownloaded, long bytesExpected) {
                // Update progress dialog with the latest progress.
                int progress = (int) (bytesDownloaded * 100 / bytesExpected);
                Log.d(TAG, String.format("Loading progress: %d percent", progress));
                mProgressBar.setProgress(progress);
            }
        };
        DriveFile driveFile = mSelectedFileDriveId.asDriveFile();
        driveFile.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, listener)
                .setResultCallback(driveContentsCallback);
        mSelectedFileDriveId = null;
    }

    private final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
            new ResultCallback<DriveApi.DriveContentsResult>() {
                @Override
                public void onResult(@NonNull DriveApi.DriveContentsResult result) {
                    if (!result.getStatus().isSuccess()) {
                        Log.w(TAG, "Error while opening the file contents");
                        return;
                    }
                    Log.i(TAG, "File contents opened");
                    
                    // Read from the input stream an print to LOGCAT
                    DriveContents driveContents = result.getDriveContents();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(driveContents.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            builder.append(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String contentsAsString = builder.toString();
                    Log.i(TAG, contentsAsString);

                    // Close file contents
                    driveContents.discard(mGoogleApiClient);
                }
            };
}
halfer
  • 19,824
  • 17
  • 99
  • 186
BNK
  • 23,994
  • 8
  • 77
  • 87
  • 4
    Error while opening the file contents – Amit kumar Jun 26 '16 at 05:44
  • 1
    Post the screenshot or logcat contain that error message, my code has been tested with a .txt file and a .jpg file in my Google Drive – BNK Jun 26 '16 at 05:55
  • 1
    06-26 11:20:39.815 24640-24640/com.google.android.gms.drive.sample.demo I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@266f8698 time:412814845 06-26 11:20:45.585 24640-24640/com.google.android.gms.drive.sample.demo I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@266f8698 time:412820613 06-26 11:20:48.475 24640-24640/com.google.android.gms.drive.sample.demo D/retrieve_contents﹕ Loading progress: 0 percent 06-26 11:20:49.495 24640-24640/com.google.android.gms.drive.sample.demo W/retrieve_contents﹕ Error while opening the file contents – Amit kumar Jun 26 '16 at 06:03
  • 1
    Which file did you open? Moreover, can you post the screenshot of your app when open that file? – BNK Jun 26 '16 at 06:09
  • 1
    And please try with other files (for example some text files, some .jpg files, make sure the files are not corrupted) – BNK Jun 26 '16 at 06:14
  • getting started.pdf – Amit kumar Jun 26 '16 at 06:14
  • For PDF files, have you used `application/pdf` with `setMimeType` method yet? – BNK Jun 26 '16 at 06:16
  • My logcat with a PDF file `D/GoogleDrive: Loading progress: 0 percent ... D/GoogleDrive: Loading progress: 100 percent I/GoogleDrive: File contents opened I/GoogleDrive: %PDF-1.5%����1 0 obj<< /Type /Catalog ...>>startxref2242%%EOF`, I think you can check with some other files – BNK Jun 27 '16 at 03:34
  • I am trying it but can't click on any file disable click on drive why?? – Sunil Chaudhary Nov 21 '16 at 12:07
  • @SunilChaudhary I think you should read https://developers.google.com/drive/v3/web/enable-sdk and https://developers.google.com/drive/android/auth – BNK Nov 22 '16 at 01:29
  • i did this can't Select means mimetype is not supported I am trying to backup db file to drive but when it save to drive its file type change from file to Unknown and then when getting it Using driveIntent can Select – Sunil Chaudhary Nov 22 '16 at 06:38
  • @SunilChaudhary try using `zip` or `rar` file instead, perhaps some useful links http://stackoverflow.com/questions/11894772/google-drive-mime-types-listing https://developers.google.com/drive/v3/web/mime-types – BNK Nov 22 '16 at 06:49
  • @BNK I received contentsAsString. i given all MIME type. I tried to write this content in device memory. I written successfully. But i am not able to open file. I tried with PDF, image – selva_pollachi Feb 01 '17 at 06:15
  • @selva_pollachi I have not tried writing files, however, please check your code as Google's guided at https://developers.google.com/drive/android/files, from "Writing files" section – BNK Feb 06 '17 at 02:00
  • I am reading xls file from drive and writing it into "download.xls" file created by me. Contents gets written successfully but when i open the file, it says file contents corrupted. – Jaydip Kalkani Aug 29 '18 at 11:36