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!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I can download video and image, but it was not playable (file format isn't supported, or is the file corrupted?).
I get stuck to get the playable video from google drive.
Any help is appreciable.
-My button onclick to intent google drive.
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickOpenFile(v);
}
});
public void onClickOpenFile(View view) {
fileOperation = false;
// create new contents resource
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
Open list of folder and file of the Google Drive
public void OpenFileFromGoogleDrive() {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"image/jpeg", "image/png", "video/mp4"
, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Unable to send intent", e);
}
}
final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.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) {
video_url = "https://drive.google.com/open?id=" + mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(video_url));
startActivity(i);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
I'm making an app that'll allows me to get a google drive files to my app. I have managed to open the google drive and to download a file to my phone but that's not the point to this app. I'm trying to open the files from the app, not to open the Google Drive. Any help?
Note: I've already registered my app at Google cloud console and all of the stuff there.
Here's the code. But as i said i don't need to open the Google Drive, i need to get files from there in my app.
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient != null) {
// disconnect Google API client connection
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
public void onConnected(Bundle connectionHint) {
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
public void onClickCreateMethod(View view){
fileOperation = true;
// create new contents resource
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
public void onClickOpenFileMethod(View view){
fileOperation = false;
// create new contents resource
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
/**
* Open list of folder and file of the Google Drive
*/
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 (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (result.getStatus().isSuccess()) {
if (fileOperation == true) {
CreateFileOnGoogleDrive(result);
} else {
OpenFileFromGoogleDrive();
}
}
}
};
public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result){
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("Hello abhay!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("abhaytest2")
.setMimeType("text/plain")
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (result.getStatus().isSuccess()) {
Toast.makeText(getApplicationContext(), "file created: "+""+
result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
}
return;
}
};
#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() + "");
String url = "https://drive.google.com/open?id=" + mFileId.getResourceId();
new DownloadFileFromURL().execute(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
DriveFile googleDriveFile = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
DriveResource.MetadataResult mdRslt = googleDriveFile.getMetadata(mGoogleApiClient).await();
if(mdRslt!= null && mdRslt.getStatus().isSuccess()){
mdRslt.getMetadata().getTitle();
System.out.println("The title is : " + driveId);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public Context getAppContext() {
return appContext;
}
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 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.
I'm convert from a googledrive example to my class that can handle It easier.
On this example, It call a menthod that return an Intent (this intent used to choose google account).
Main activity call startActivityForResult(intent). and check session & login on onActivityResult.
The googledrive example
public class GoogleActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int CAPTURE_IMAGE = 3;
private static Uri fileUri;
private static Drive service;
private GoogleAccountCredential credential;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
//Start account picker here (the intent I've told above)
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
//credential.newChooseAccountIntent() return an intent that can choose google account
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
//Process it when intent exit
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
startCameraIntent();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
break;
case CAPTURE_IMAGE:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
}
}
}
private void startCameraIntent() {
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
fileUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_" + timeStamp + ".jpg"));
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAPTURE_IMAGE);
}
private void saveFileToDrive() {
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());
startCameraIntent();
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
}
Now I want to create a class to handle some feature of googledrive including login. My Login() menthod handle everything about login.
I can call Account Picker intent outside main activity but I can't handle when that intent exit/destroy.
My class is something like this:
public class GoogleHandler {
Activity act;
public GoogleHandler(Activity act) {
this.act = act;
}
public void Login() {
//start
act.startActivity(intent, requestCode);
}
// And then, how to handle when intent exit ??
}
Any suggestion also helped me.
The Intent that you pass to startActivity() doesn't ever start or finish. That's not what Intents do; Intents start up another Activity (or Service), which then starts and finishes.
When the Google Account Picker Activity finishes, the onActivityResult() method of the calling Activity is called. In your example, act recvieves a call to onActivityResult(). You can see an example of how to properly use the result in the Google Drive sample code you posted.
In order to properly receive this callback, the act Activity must override onActivityResult(). You cannot do this within the Login() method or the GoogleHandler class unless you change GoogleHandler to an Activity.