googleworkspace / android-samples

Android samples for Google Workspace APIs
Apache License 2.0
636 stars 410 forks source link

Got issue while downloading file from google drive #54

Closed ravi-vihaaInfotech closed 6 years ago

ravi-vihaaInfotech commented 7 years ago

I have created demo Application for google drive file sharing into my server. Below is my Process 

private class FileDownloadTask extends AsyncTask<String, Void, String> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = ProgressDialog.show(FileExplorerActivity.this, "", true, false, null);
}

@Override
protected String doInBackground(String... arg0) {
    downloadFileToSdCard();
    return null;
}

@Override
protected void onPostExecute(String s) {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
    }
    super.onPostExecute(s);
    Intent intent = new Intent();
    intent.putExtra("filePath", Const.DOC_PATH + "/" + fileName);
    setResult(RESULT_OK, intent);
    finish();
}

private void downloadFileToSdCard() {
    try {
        selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(contentsOpenedCallback);
    } catch (Exception io) {
        io.printStackTrace();
    }
}

}

ResultCallback contentsOpenedCallback = new ResultCallback() { @Override public void onResult(DriveApi.DriveContentsResult result) { if (!result.getStatus().isSuccess()) { return; }

            try {

                File dir = new File(Const.DOC_PATH);
                if (dir.exists() == false) {
                    dir.mkdirs();
                }
                String fName = fileName;
                File file = new File(dir, fName);
                if (file.exists())
                    file.delete();

                FileOutputStream fos = new FileOutputStream(file);
                DriveContents driveContents = result.getDriveContents();
                byte[] buffer = new byte[1024];
                int bufferLength = 0;
                InputStream inputStream = driveContents.getInputStream();
                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, bufferLength);
                }
                driveContents.discard(getGoogleApiClient());
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
asrivas commented 6 years ago

Are you still having this issue?

asrivas commented 6 years ago

DriveApi.DriveContentsResult has been deprecated, please let us know if you are still having issues with the new recommendation. https://developers.google.com/android/reference/com/google/android/gms/drive/DriveApi.DriveContentsResult