I am working on an android app, which should be able to read a spreadsheet from google drive. However, every time when I try to open a file from google drive I get following message from the DriveContentsResult: "No content is available for this file".
Here is my code, after I got the authorization for google drive via the GoogleApiClient:
private static final int REQUEST_RESOLVE_ERROR = 1001;
public static final int REQUEST_CODE_OPENER = 1002;
private DriveId mSelectedFileDriveId;
public GoogleApiClient mGoogleApiClient;
public void getGoogleDriveFile(View view){
if(mGoogleApiClient.isConnected()){
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[] {"application/vnd.google-apps.spreadsheet"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.d(TAG, "Unable to send intent" + e);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult");
if (requestCode == REQUEST_RESOLVE_ERROR) {
...
} else if(requestCode == REQUEST_CODE_OPENER){
if(resultCode == RESULT_OK){
mSelectedFileDriveId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
if(mSelectedFileDriveId != null){
open();
}
}
}
}
private void open() {
Drive.DriveApi.getFile(mGoogleApiClient, mSelectedFileDriveId)
.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(driveContentsCallback);
}
private ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.d(TAG, "Error while opening the file contents " + result.getStatus().getStatusMessage());
return;
}
DriveContents contents = result.getDriveContents();
}
};
Content here refers to binary content. Google Spreadsheets (and the other Google Docs types) are not stored as binary content. The Android-specific API doesn't currently support reading Spreadsheet contents.
Using the RESTful API, you can get it in a binary format like csv using the ExportLinks.
use the "google spreadsheets api" (REST) not drive api.
Related
I have implemented Google Drive with my Android application. I am able to view all my files in the app. Now I want to implement delete and update of google drive files.
This is my current code:
public void OpenFileFromGoogleDrive() {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"text/plain", "text/html"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
}
catch (SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
final ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (result.getStatus().isSuccess()) {
OpenFileFromGoogleDrive();
}
}
};
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + ""); // 0B-KGM98PVf2SdkdYTFRXZlNjSjg
/*String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);*/
options();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
How to delete and update files using DriveId?
You can achieve this doing:
driveFile = Drive.DriveApi.getFile(mGoogleApiClient,
DriveId.decodeFromString(driveIdStr));
// Call to delete file.
driveFile.delete(mGoogleApiClient).setResultCallback(deleteCallback);
Check google drive documentation for more info https://developers.google.com/drive/android/trash?hl=es-419
In addition to #AndroidRuntimeException's answer, you may want to check this Working with File Contents documentation and this Google Drive Android API Demos.
To edit a file:
/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = result.getDriveId();
DriveFile file = driveId.asDriveFile();
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
To delete a file:
/**
* An activity to illustrate how to delete contents of a Drive file.
*/
driveFile = Drive.DriveApi.getFile(mGoogleApiClient,
DriveId.decodeFromString(driveIdStr));
// Call to delete file.
driveFile.delete(mGoogleApiClient).setResultCallback(deleteCallback);
Hope this helps!
Im using the Drive.DriveApi in Android. Exporting and then Importing a file from within my Android App to Google Drive works in both directions.
I can also access the file and download it from a Web browser to my local Mac.
However if I first upload a new file to Google Drive with my Mac and then later try to access this file from my Android App and Import it, I can't access the file. I can see the file, but it is greyed out.
Im using the same user both on the Android App as online on my Mac with Google Drive.
Anyone?
My code I use.
Import:
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"application/csv"})
.build(activity.getGoogleClient());
try {
activity.startIntentSenderForResult(intentSender, DRIVE_REQUEST_CODE_OPENER_IMPORT, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent: ", e);
}
Export:
Drive.DriveApi.newDriveContents(activity.getGoogleClient()).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
Uri csvUri = Uri.parse("file://" + getCsvFile(context));
File csvFile = new File(csvUri.getPath());
if(csvFile.length() <= 0) {
Log.e(TAG, "File empty: " + getCsvFile(context));
}
FileInputStream csvInputStream = null;
try {
csvInputStream = new FileInputStream(csvFile);
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
byte[] dataArray = IOUtils.toByteArray(csvInputStream);
outputStream.write(dataArray);
} catch (FileNotFoundException fnfe) {
Log.e(TAG, "File not found: ", fnfe);
} catch (IOException ie) {
Log.e(TAG, "Error uploading file: ", ie);
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder().setMimeType("application/csv").setTitle(getCsvFilename()).build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(driveContentsResult.getDriveContents())
.build(activity.getGoogleClient());
try {
activity.startIntentSenderForResult(intentSender, DRIVE_REQUEST_CODE_OPENER_EXPORT, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent: ", e);
}
}
});
onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
final Uri csvUri = Uri.parse("file://" + getCsvFile(context));
final File csvFile = new File(csvUri.getPath());
if(requestCode == DRIVE_REQUEST_CODE_OPENER_IMPORT && resultCode == activity.RESULT_OK && data != null) {
DriveId driveId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.i(TAG, "Selected file's ID: " + driveId);
driveId.asDriveFile().open(activity.getGoogleClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
try {
InputStream input = driveContentsResult.getDriveContents().getInputStream();
byte[] dataArray = IOUtils.toByteArray(input);
FileUtils.writeByteArrayToFile(csvFile, dataArray);
finish.onImportFinished();
} catch (IOException ie) {
Log.e(TAG, "Error downloading file: ", ie);
}
}
});
} else if(requestCode == DRIVE_REQUEST_CODE_OPENER_EXPORT && resultCode != activity.RESULT_CANCELED) {
finish.onExportFinished();
}
csvFile.delete(); // Always delete to avoid readable file on disk
}
Can't select file vault.csv
Update1:
public void initGoogleClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
Update2:
If I however first export a file from within my Android app. Then download the file from my browser on my Mac, add some data. Upload it from my Mac.
Now importing this file from my Android app works.
Is there a way to change the privileges on a newly uploaded file via the WEB Google Drive interface? Other comments?
Update3 my Mac Google Drive browser:
Changed MIME type to
.setMimeType(new String[]{"text/csv"})
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.
IMO, you should read some useful links below:
Google Drive APIs Android - Guides - Working with File Contents
Google Drive Android API Demos at GitHub
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);
}
};
}
I am launching an intent to get photos from gallery and when I am using nexus google photo app in my gallery everything works fine.
But if the image is not on the phone (on the Google Photos online service) it will download it for me. After selecting the image I am sending the image to another activity for cropping but in case of download the image sent to the crop activity is null since the download is not finished yet.
How can I know when the download is finished to send the image to the cropping activity?
Here is my code:
private void pickFromGallery()
{
Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
startCrop(imgDecodableString);
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
any help would be appreciated.
I think you can't crop images when you download selected image from google photos. you can only crop your local storage images
But for checking whether selected image is downloadable or from local storage you can do like this in your onActivityResult() method.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
String url = data.getData().toString();
if (url.startsWith("content://com.google.android.apps.photos.content")){
try {
InputStream is = getActivity().getContentResolver().openInputStream(selectedImageUri);
if (is != null) {
Bitmap pictureBitmap = BitmapFactory.decodeStream(is);
//You can use this bitmap according to your purpose or Set bitmap to imageview
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
startCrop(tempPath);
}
}
}
Here is getPath() method which is used in onActivityResult().
public String getPath(Uri uri, Activity activity) {
Cursor cursor = null;
try {
String[] projection = {MediaStore.MediaColumns.DATA};
cursor = activity.getContentResolver().query(uri, projection, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
return cursor.getString(column_index);
}
} catch (Exception e) {
} finally {
cursor.close();
}
return "";
}
I hope it helps you.
you can not download images from google drive below are the steps to download images or files from drive.
To download images or file from google drive you need a library
google-api-services-drive-v2-rev9-1.8.0-beta.jar()
SETTING UP THE CONSOLE
next go to Google Consol
Make a new project. Under Services, you'll need to turn on two things: DRIVE API and DRIVE SDK! They are separate, one does not automatically turn the other on, and YOU MUST TURN BOTH ON! (Figuring this out wasted at least 20 hours of my time alone.)
Still on the console, go to API Access. Create a client, make it an Android app. Give it your bundle ID. I don't think the fingerprints thing is actually important, as I'm pretty sure I used the wrong one, but try to get that right anyways (Google provides instructions for it.)
It'll generate a Client ID. You're going to need that. Hold onto it.
THE ANDROID CODE - Set Up and Uploading
First, get an auth token:
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
Next, OnTokenAcquired() needs to be set up something like this:
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JSonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.)
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(activity);
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken (same as before...)
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
THE ANDROID CODE - Downloading
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
if (jFolder == null) {
jFolder = Environment.getExternalStorageDirectory();
jFolder.mkdirs();
}
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(gFile.getDownloadUrl());
get.setHeader("Authorization", "Bearer " + token);
HttpResponse response = client.execute(get);
InputStream inputStream = response.getEntity().getContent();
jFolder.mkdirs();
java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
FileOutputStream fileStream = new FileOutputStream(jFile);
byte buffer[] = new byte[1024];
int length;
while ((length=inputStream.read(buffer))>0) {
fileStream.write(buffer, 0, length);
}
fileStream.close();
inputStream.close();
return jFile;
} catch (IOException e) {
// Handle IOExceptions here...
return null;
}
} else {
// Handle the case where the file on Google Drive has no length here.
return null;
}
}
You can use AsyncTask for downloading (or copying local image), then process it.
In your Activity create:
private class PictureAsyncTask extends AsyncTask<Void, Void, String> {
private Uri mUri;
public PictureAsyncTask(Uri uri) {
mUri = uri;
}
#Override
protected String doInBackground(Void... params) {
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(mUri);
String path = null; // Path of downloaded image
// Download image from inputStream
return path;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null
}
#Override
protected void onPostExecute(String path) {
if (path == null) {
// Process image
// Maybe another AsyncTask or background thread?
} else {
// Download failed
}
}
}
Call it from onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_LOAD_IMG:
if (resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
new PictureAsyncTask(uri).execute();
} else {
// No data
}
} else {
// No picture selected?
}
}
break;
}
}
Once I logged in gdrive I tried to upload csv file programmatically. But it throws error in service.
public class Gdriveactivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "android-drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
private void saveFiletoDrive() {
ResultCallback<DriveApi.ContentsResult> contentsCallback = new
ResultCallback<DriveApi.ContentsResult>() {
#Override
public void onResult(DriveApi.ContentsResult result) {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("New file")
.setMimeType("text/plain").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, null /* DriveContents */)
.setResultCallback(this);
}
};
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
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) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// Just start the camera again for another photo.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
Toast.makeText(Gdriveactivity.this, "connected failed", 1000).show();
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// Called typically when the app is not yet authorized,
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
Toast.makeText(Gdriveactivity.this, "connected", 1000).show();
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
// REQUEST_CODE_CAPTURE_IMAGE);
// return;
}
insertFile();
}
Once I connected to gdrive account only I tried to upload file. But it shows error in service.
I can't use Drive service to initialize also because I imported drive in gms way
import com.google.android.gms.drive.Drive;
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;
There are a number of methods of Creating a Google Drive File including using a CreateFileActivityBuilder to allow the user to pick exactly where on their Google Drive they would like to create the file or programmatically calling createFile() on a DriveFolder you have. Ways of retrieving the appropriate DriveFolder include:
Drive.DriveApi.getRootFolder() (for the public root directory)
Drive.DriveApi.getAppFolder() (for your application private directory - the user cannot see these files, only how much storage space they take)
through a result of Drive.DriveApi.query().