I want to read the i have written on a file in Appfolder.but i am not able to read that my app is crashes when i try to read that from file.i have created the file in App folder successfully.i am using the below code so please tell if i am doing anything wrong.The error which is coming while i run this code is invalid drive id.i am getting that drive id by this:
result.getDriveFile().getDriveId().encodeToString()
where result is drivefileresult. May I know what is the correct way to achieve my objective?
public class Fifth extends BaseDemoActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
}
#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;
}
// Get an output stream for the contents.
OutputStream outputStream = result.getContents().getOutputStream();
// Write the bitmap data from it.
String data="hello world. this is sample";
byte[] bytes = data.getBytes();
// ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
// image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
Log.i("Success", "able to write file contents.");
outputStream.write(bytes);
} catch (IOException e1) {
Log.i("Failier", "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("appdatafolder.txt")
.setMimeType("text/plain")
.build();
Drive.DriveApi.getAppFolder(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 in App Folder: "
+ result.getDriveFile().getDriveId());
Log.i("Drioved_ID", result.getDriveFile().getDriveId().encodeToString());
}
};
}
Unfortunately I don't have time to analyze your code but can offer a segment that does essentially the same. Try it.
GoogleApiClient gac = getGoogleApiClient();
DriveFolder dfl = Drive.DriveApi.getAppFolder(gac)
String title = "appdatafolder.txt";
String mime = "text/plain";
byte[] buff = ("hello world. this is sample").getBytes();
createFile(gac, dfl, title, mime, buff);
void createFile(final GoogleApiClient gac, final DriveFolder fldr,
final String name, final String mime, final byte[] buff) {
Thread t = new Thread(new Runnable() {
#Override public void run() {
try {
ContentsResult rslt = Drive.DriveApi.newContents(gac).await();
if (rslt.getStatus().isSuccess()) {
Contents cont = rslt.getContents();
cont.getOutputStream().write(buff);
MetadataChangeSet meta =
new MetadataChangeSet.Builder().setTitle(name).setMimeType(mime).build();
DriveFile df = fldr.createFile(gac, meta, cont).await().getDriveFile();
Log.i("X", ""+ df.getDriveId().encodeToString());
}
} catch (Exception e) {}
}
});
t.start();
}
... and here is how you read it back:
void getFileIs(final GoogleApiClient gac, final DriveId drvId) {
Thread t = new Thread(new Runnable() {
#Override public void run() {
try {
DriveFile df = Drive.DriveApi.getFile(gac, drvId);
ContentsResult rslt = df.openContents(gac, DriveFile.MODE_READ_ONLY, null).await();
if (rslt.getStatus().isSuccess()){
InputStream is = rslt.getContents().getInputStream();
}
} catch (Exception e) {}
}
});
t.start();
}
After days of searching for a good example, I found the Google I/O app on GitHub has excellent utility methods to create, update and read files from Drive. They use the AppFolder as well.
Related
I used the following Drive API code in Android for download files from Google Drive.
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(GoogleDriveActivity.this);
DriveClient mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
DriveResourceClient mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
By using this code I am able to download all files i.e Docx, Doc, Image, xls, xlsx, txt, pdf etc.
but it has given the issue for the following files.
Google Doc (application/vnd.google-apps.document),
SpreadSheet (application/vnd.google-apps.spreadsheet),
Presentation file (application/vnd.google-apps.presentation)
even I tried to change metadata for the selected file by using this code but still, its shown file size is 0 (Zero) and
the extension is null.
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setMimeType(Constants.MIME_TYPE_DOCX)
.build();
Task<Metadata> updateMetadataTask =
mDriveResourceClient.updateMetadata(file, changeSet);
So please suggest the solution if anybody implemented it.
I tried to download Google Doc, Spreadsheet and Presentation file by using Google Drive Android API but didn’t get any proper solution for it by using Drive API.
But I have read in many places that you can download this documents using REST. Finally, I got the right solution for it when I combined both these codes i.e. Drive API Code and REST code
Here is the code for it.
First, you need to add these two lines in your build.gradle file in App module.
compile('com.google.api-client:google-api-client-android:1.23.0') {
exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev107-1.23.0') {
exclude group: 'org.apache.httpcomponents'
}
Second, Initialize GoogleAccountCredential and Drive by your selected account.
private com.google.api.services.drive.Drive driveService = null;
private GoogleAccountCredential signInCredential;
private long timeStamp;
private String fileName;
// Initialize credentials and service object.
signInCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
if (!TextUtils.isEmpty(signInAccount.getAccount().name)) {
signInCredential.setSelectedAccountName(signInAccount.getAccount().name);
signInCredential.setSelectedAccount(new Account(signInAccount.getAccount().name, getPackageName()));
}
if (!TextUtils.isEmpty(signInCredential.getSelectedAccountName())) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
driveService = new com.google.api.services.drive.Drive.Builder(transport, jsonFactory, signInCredential)
.setApplicationName(appName)
.build();
}
//Pass two parameters i.e fileId and mimeType which one you get when you select the file name.
public void retrieveGoogleDocContents(String fileId, String mimeType) throws IOException {
try {
File storageDir =createStorageDir();
timeStamp = System.currentTimeMillis();
//selectedFileName which one you get when you select any file from the drive, or you can use any name.
fileName = selectedFileName + "." +getFileExtension(mimeType);
File localFile = new File(storageDir, timeStamp + "_" + fileName);
if (!localFile.exists()) {
if (localFile.createNewFile())
Log.d(TAG, fileCreated);
}
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean isSuccess = false;
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(localFile);
com.google.api.services.drive.Drive.Files.Export request = driveService.files().export(fileId,getFileMimeType(mimeType));
request.getMediaHttpDownloader().setProgressListener(new GoogleDriveActivity.CustomProgressListener());
request.getMediaHttpDownloader().setDirectDownloadEnabled(false);
request.executeMediaAndDownloadTo(outputStream);
isSuccess = true;
} catch (UserRecoverableAuthIOException e) {
Log.d(TAG, "REQUEST_AUTHORIZATION Called");
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} finally {
close(outputStream);
}
return isSuccess;
}
#Override
protected void onPostExecute(Boolean isSuccess) {
Log.i(TAG, "Download Successfully :" + isSuccess);
}
};
task.execute();
} catch (IOException e){
Log.e(TAG, e.toString());
}
}
public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
public static File createStorageDir() {
String path = Environment.getExternalStorageDirectory() + "/" + Constants.IMAGE_DIRECTORY;
File storageDir = new File(path);
if (!storageDir.exists()) {
if (storageDir.mkdir())
Log.d(TAG, "Directory created.");
else
Log.d(TAG, "Directory is not created.");
} else
Log.d(TAG, "Directory exist.");
return storageDir;
}
Here are file mime type and extension.
public final static String ICON_DOCX = "docx";
public final static String ICON_PPTX = "pptx";
public final static String ICON_XLSX = "xlsx";
public final static String MIME_TYPE_GOOGLE_DOC = "application/vnd.google-apps.document";
public final static String MIME_TYPE_GOOGLE_SPREADSHEET = "application/vnd.google-apps.spreadsheet";
public final static String MIME_TYPE_GOOGLE_PRESENTATION = "application/vnd.google-apps.presentation";
public final static String MIME_TYPE_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public final static String MIME_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public final static String MIME_TYPE_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
public static String getFileExtension(String fileMimeType) {
String fileExtension = Constants.ICON_PDF;
if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
fileExtension = Constants.ICON_DOCX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
fileExtension = Constants.ICON_XLSX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
fileExtension = Constants.ICON_PPTX;
return fileExtension;
}
public static String getFileMimeType(String fileMimeType) {
String newMimeType = Constants.MIME_TYPE_PDF;
if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
newMimeType = Constants.MIME_TYPE_DOCX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
newMimeType = Constants.MIME_TYPE_XLSX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
newMimeType = Constants.MIME_TYPE_PPTX;
return newMimeType;
}
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 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.