In my project I have to backup and restore .db SQLite database to google drive. I looked through google documentation and demo project. I have problem with DRIVE ID.
that's my client:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
I've created file as google showed:
public class CreateFileActivity extends BaseDemoActivity {
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newContents(getGoogleApiClient())
.setResultCallback(contentsCallback);
}
final private ResultCallback<ContentsResult> contentsCallback = new
ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("testFile.txt")
.setMimeType("text/plain")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file: " + result.getDriveFile().getDriveId());
Log.e("misha", ""+result.getDriveFile().getDriveId() );
}
};
}
Then retrieved it's drive ID with quering files by my filne name and printed it to Log :
public class QueryFilesActivity extends BaseDemoActivity {
private ListView mResultsListView;
private ResultsAdapter mResultsAdapter;
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_listfiles);
mResultsListView = (ListView) findViewById(R.id.listViewResults);
mResultsAdapter = new ResultsAdapter(this);
mResultsListView.setAdapter(mResultsAdapter);
}
/**
* Clears the result buffer to avoid memory leaks as soon
* as the activity is no longer visible by the user.
*/
#Override
protected void onStop() {
super.onStop();
mResultsAdapter.clear();
}
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Query query = new Query.Builder()
//.addFilter(Filters.eq(SearchableField.MIME_TYPE, "text/plain"))
.addFilter(Filters.eq(SearchableField.TITLE, "testFile.txt"))
.build();
Drive.DriveApi.query(getGoogleApiClient(), query)
.setResultCallback(metadataCallback);
}
final private ResultCallback<MetadataBufferResult> metadataCallback = new
ResultCallback<MetadataBufferResult>() {
#Override
public void onResult(MetadataBufferResult result) {
MetadataBuffer metaData = result.getMetadataBuffer();
for (int i = 0 ; i <metaData.getCount(); i++){
Log.e("misha", metaData.get(i).getDriveId().toString());
}
if (!result.getStatus().isSuccess()) {
showMessage("Problem while retrieving results");
return;
}
mResultsAdapter.clear();
mResultsAdapter.append(result.getMetadataBuffer());
}
};
}
So, I have not\w my file's Drive Id XXXXXXXXXXZiUUxXM0lIUWFhV0pFV0hwSFVqWXhXRzgY9AXXXXXXXXXX. I guess it's correct ID. now when I want to get Contents of file. I get the following error
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
Cannot find DriveId. Are you authorized to view this file?
I want to get contents of the file, also I want to change the contents and so on. But I stuck at retrieving file contents :( please help guys
Related
I am facing the issue in creating the file inside a folder , i created the separate file and separate folder in google drive but i can't create the file inside a folder in google drive
I have used the for creating the file inside the folder in google drive is posted below
public void onClickFolderInRootFlder(View view)
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("New CallLog folders").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient).createFolder(
mGoogleApiClient, changeSet).setResultCallback(callback);
}
final ResultCallback<DriveFolder.DriveFolderResult> callback = new ResultCallback<DriveFolder.DriveFolderResult>() {
#Override
public void onResult(DriveFolder.DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(MainActivity.this,"Error while trying to create the folder",Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(MainActivity.this,"Created a folder with content: " +
result.getDriveFolder().getDriveId(),Toast.LENGTH_SHORT).show();
Drive.DriveApi.fetchDriveId(mGoogleApiClient, String.valueOf(result.getDriveFolder().getDriveId()))
.setResultCallback(idCallback);
}
};
final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
// showMessage("Cannot find DriveId. Are you authorized to view this file?");
Toast.makeText(MainActivity.this,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_SHORT).show();
return;
}
DriveId mFolderDriveId = result.getDriveId();
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
};
final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
// display an error saying file can't be opened
return;
}
else{
CreateFileOnGoogleDrive(result);
}
// DriveContents object contains pointers
// to the actual byte stream
DriveContents contents = result.getDriveContents();
}
};
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 World");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("prabha")
.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(MainActivity.this,"Error while trying to create the file",Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(MainActivity.this,"Created a file with content: " +
result.getDriveFile().getDriveId(),Toast.LENGTH_SHORT).show();
}
};
I tried this method but the issue is occurring in the line
final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
// showMessage("Cannot find DriveId. Are you authorized to view this file?");
Toast.makeText(MainActivity.this,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_SHORT).show();
return;
}
DriveId mFolderDriveId = result.getDriveId();
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
};
The result.getStatus.isSuccess is false is returning .Please help me how to create the file inside a folder in google drive.
You are calling
Drive.DriveApi.getRootFolder(mGoogleApiClient).createFile
which (unsurprisingly) creates a file in the Root Folder.
Instead you should call
DriveFolder.createFile
as described at https://developers.google.com/android/reference/com/google/android/gms/drive/DriveFolder.html#createFile(com.google.android.gms.common.api.GoogleApiClient,com.google.android.gms.drive.MetadataChangeSet,com.google.android.gms.drive.DriveContents)
Using the bellow snippet I am able to access folder which I have already created with the same app. I am using 'com.google.android.gms:play-services-drive:9.0.0' library and referring google drive sample on github. using the sample CreateFolderInFolderActivity.java I am able to create folder inside an existing folder. Instead of creating folder I need to create a file inside existing folder.
public class CreateFileInsideFolderActivity extends BaseDemoActivity {
private static final String TAG = "CreateFileActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Drive.DriveApi
.fetchDriveId(getGoogleApiClient(), "0B_cMuo4-XwcAZ3IzSG1jajFlWk0")
.setResultCallback(idCallback);
}
final ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = result.getDriveId();
//showMessage("driveid" + driveId.getResourceId());
final DriveFolder folder = driveId.asDriveFolder();
//
// How to upload a file to this folder
//
}
Thanks #pinoyyid
I fount an example from wiki.workassis that I am sharing here. If anyone have better solution please share with me
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(driveContentsCallback);
}
In result call back
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
OutputStream outputStream = driveContents.getOutputStream();
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
if (inputStream != null) {
byte[] data = new byte[1024];
while (inputStream.read(data) != -1) {
outputStream.write(data);
}
inputStream.close();
}
outputStream.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("New file")
.setMimeType("image/jpg")
.setStarred(true).build();
DriveApi.DriveIdResult exFolderResult = Drive.DriveApi
.fetchDriveId(getGoogleApiClient(), ExistingFolderID)
.await();
if (!exFolderResult.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = exFolderResult.getDriveId();
//showMessage("driveid" + driveId.getResourceId());
final DriveFolder folder = driveId.asDriveFolder();
// create a file on root folder
folder.createFile(getGoogleApiClient(), changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
I am using the default file picker for getting Image url
refer : http://wiki.workassis.com/google-drive-android-api-upload-file-to-existing-folder/
for file picker : http://wiki.workassis.com/android-create-a-file-picker/
I'm trying using the Google API for Android to create a file, search, download and delete in the app folder.
But i'm getting some problems...
If i use the 'getRootFolder()' to save my file everything works. But, if i use 'getAppFolder()' nothing works.
Example:
The user download my app, my app search if exist any created file.
If nothing return the app create a new file in AppFolder.
If the user uninstall the app and download again, the app can't reach the file.
I try 'requestSync' but nothing happens. I trying using the Listening for Changes and Receiving completion Events, they return 'Success' but still not sync the AppFolder.
I saw some similar problems, but none works for me.
If i use the 'getRootFolder()' everything works great...
Can you guys help?
Here some Code Examples:
OnConnected:
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (sharedPreferences.getBoolean("automaticBackup", true)) {
String FILE_PATH = this.getDatabasePath(DataHelper.DATABASE_NAME).getPath();
String extension = MimeTypeMap.getFileExtensionFromUrl(FILE_PATH);
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
file = new File(FILE_PATH);
if (hasInternetAccess()) {
if (sharedPreferences.getBoolean("firstUse", true)) {
Drive.DriveApi.query(getGoogleApiClient(), query).setResultCallback(restoreCallBack);
final SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("firstUse", false);
editor.apply();
} else {
// delete existing backup
Drive.DriveApi.query(getGoogleApiClient(), query).setResultCallback(checkIfFileExists);
}
}
}
}
Here i check if file exist, true delete, false create a new one:
final private ResultCallback<DriveApi.MetadataBufferResult> checkIfFileExists = new ResultCallback<DriveApi.MetadataBufferResult>() {
private DriveId fileId;
#Override
public void onResult(#NonNull DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while checking if file exists...");
return;
}
MetadataBuffer metadata = result.getMetadataBuffer();
if (metadata.getCount() > 0) {
fileId = metadata.get(0).getDriveId();
if (fileId != null) {
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), fileId.getResourceId()).setResultCallback(deleteFile);
}
} else {
Log.d(TAG, "No backup file found");
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(createBackupCallBack);
}
}
};
Here the code to delete:
final private ResultCallback<DriveApi.DriveIdResult> deleteFile = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveIdResult driveIdResult) {
final DriveId driveId = driveIdResult.getDriveId();
try {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
DriveId fileId = DriveId.decodeFromString(driveId.encodeToString());
DriveFile driveFile = fileId.asDriveFile();
com.google.android.gms.common.api.Status deleteStatus = driveFile.delete(getGoogleApiClient()).await();
if (!deleteStatus.isSuccess()) {
Log.e(TAG, "Unable to delete the old backup");
return null;
}
sharedPreferences.edit().remove(driveId.toString()).apply();
Log.d(TAG, "Removed old backup.");
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(createBackupCallBack);
}
}.execute().get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
};
Upload the file to Drive:
final private ResultCallback<DriveApi.DriveContentsResult> createBackupCallBack = new
ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
OutputStream outputStream = driveContents.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
try {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(DataHelper.DATABASE_NAME)
.setMimeType(type)
.setStarred(true).build();
Drive.DriveApi.getAppFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, driveContents)
.setResultCallback(fileCallback);
return null;
}
}.execute();
}
};
Result Call Back from upload:
final private ResultCallback<DriveApi.MetadataBufferResult> restoreCallBack = new ResultCallback<DriveApi.MetadataBufferResult>() {
DriveId driveId;
#Override
public void onResult(#NonNull DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while restoring...");
}
MetadataBuffer metadata = result.getMetadataBuffer();
if (metadata.getCount() > 0) {
File fileBD = getDatabasePath(DataHelper.DATABASE_NAME);
boolean deleted = fileBD.delete();
Log.d("DELETED", deleted + "");
driveId = metadata.get(0).getDriveId();
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), driveId.getResourceId()).setResultCallback(idCallback);
} else {
Log.d(TAG, "No backup file found!");
}
}
};
It may be permission issue. Adding drive.appfolder authorization scopes to GoogleApiClient may solve your problem. For example:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_APPFOLDER) // required to access app folder
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
mGoogleApiClient.connect();
Found a solution, you need to sync with the drive before querying the AppFolder.
Use this after connecting to the drive:
Drive.DriveApi.requestSync(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
}
});
i am building an android app using google drive api.First i get resourceId of a folder ("shared with me with edit access") using files:list rest api.i get Folder
Id="0B6DwkfjCNXHYflJVOGdnbFU0QkxfU25NbHV5UjNfVmNlNWhhcllnbktmNDNReEhuMm83X0E"
public class MainActivity extends BaseDemoActivity {
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(),"0B6DwkfjCNXHYflJVOGdnbFU0QkxfU25NbHV5UjNfVmNlNWhhcllnbktmNDNReEhuMm83X0E")
.setResultCallback(idCallback);
}
final private 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;
}
Log.i("driveId is: ", result.toString());
showMessage("Drive Id is: "+result.toString());
DriveId driveId = result.getDriveId();
Log.i("drive Id is",driveId.toString());
//showMessage("Drive Id is: " + driveId.toString());
/* DriveFile ff = driveId.asDriveFile();
ff.getMetadata(getGoogleApiClient()).setResultCallback(metadataRetrievedCallback);
*/
/* DriveFolder folder = driveId.asDriveFolder();
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.MIME_TYPE, "text/plain"))
.build();
folder.queryChildren(getGoogleApiClient(), query)
.setResultCallback(metadataCallback);*/
}
};
ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new
ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while trying to fetch metadata");
return;
}
Metadata metadata = result.getMetadata();
showMessage("Metadata succesfully fetched. Title: " + metadata.getTitle());
}
};
}
i set up the project as described in google drive android api.but when i run my code i am getting in callback error "Cannot find DriveId. Are you authorized to view this file?"
I have spent too much time on this so I would like to ask about it. I want to create and upload google spreadsheet using android. I know that I should use Drive API to do this. I know how to create file using this API(even excel file) but when setMimeType is set to application/vnd.google-apps.spreadsheet I receive an error on the device: Error while trying to create the file.
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient())
.setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
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 World!");
writer.write("Hello World!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Orders")
.setMimeType("application/vnd.google-apps.spreadsheet")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
storeId(result.getDriveFile().getDriveId());
kill_activity();
}
};v
The GDAA does not currently support creation Google Docs files. You will have to use the Google Drive REST API in your Android application to do this.
#user3212019, You can upload a excel spread sheet in google drive from your android app, just follow as below.
I think you aware of Quick Start on Google Android site.
Now create a excel sheet by using jxl jar library
Now follow the Start Integrating Google Sign-In and Integrate Google SignIn with Drive scope (Drive.SCOPE_FILE) in your app.
Now final and last copy paste below activity code in your activity and then give a excel sheet path in saveFileToDrive(file_path) method.
public class UploadFileInGoogleDriveActivity extends Activity {
private static final String TAG = "tejadroid-quickstart";
private static final int REQUEST_CODE_SIGN_IN = 0;
private GoogleSignInClient mGoogleSignInClient;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signIn();
}
/**
* Start sign in activity.
*/
private void signIn() {
Log.i(TAG, "Start sign in");
mGoogleSignInClient = buildGoogleSignInClient();
startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
/**
* Build a Google SignIn client.
*/
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(this, signInOptions);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
Log.i(TAG, "Sign in request code");
// Called after user is signed in.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Signed in successfully.");
// Use the last signed in account here since it already have a Drive scope.
mDriveClient = Drive.getDriveClient(this, GoogleSignIn.getLastSignedInAccount(this));
// Build a drive resource client.
mDriveResourceClient =
Drive.getDriveResourceClient(this, GoogleSignIn.getLastSignedInAccount(this));
// Excel Sheet path from SD card
final String filePath = "/storage/emulated/0/Expense Manager/ExpenseReport/ExpenseDiary.xls";
saveFileToDrive(filePath);
}
break;
}
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final String filePath) {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
mDriveResourceClient
.createContents()
.continueWithTask(
new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
return createFileIntentSender(task.getResult(), new File(filePath));
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Failed to create new contents.", e);
}
});
}
/**
* Creates an {#link IntentSender} to start a dialog activity with configured {#link
* CreateFileActivityOptions} for user to create a new photo in Drive.
*/
private Task<Void> createFileIntentSender(DriveContents driveContents, File file) throws Exception {
Log.i(TAG, "New contents created.");
OutputStream outputStream = driveContents.getOutputStream();
InputStream in = new FileInputStream(file);
try {
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
outputStream.close();
}
} finally {
in.close();
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet =
new MetadataChangeSet.Builder()
.setMimeType("application/vnd.ms-excel")
.setTitle("ExcelSheet.xls")
.build();
// Set up options to configure and display the create file activity.
CreateFileActivityOptions createFileActivityOptions =
new CreateFileActivityOptions.Builder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(driveContents)
.build();
return mDriveClient
.newCreateFileActivityIntentSender(createFileActivityOptions)
.continueWith(
new Continuation<IntentSender, Void>() {
#Override
public Void then(#NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0);
return null;
}
});
}
}
Just debug app and look in to Google Drive there your file exist in root folder of drive.