How I can create and upload google spreadsheet using android app? - android

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.

Related

OnResult never called after DriveApi.NewDriveContent

I'm trying to create a file on google drive through android, I successfully sign in google but when I try to create a drive content I don't receive the OnResult.
This is my code:
public class GoogleDrive: Java.Lang.Object, IResultCallback
{
GoogleApiClient GAClient;
public GoogleDrive(Android.Content.Res.Resources res,GoogleApiClient gac)
{
GAClient=gac;
DriveClass.DriveApi.NewDriveContents(GAClient).SetResultCallback(this);
}
void IResultCallback.OnResult(Java.Lang.Object result)
{
var contentResults = (result).JavaCast<IDriveApiDriveContentsResult>();
Statuses a=contentResults.Status;
if (!contentResults.Status.IsSuccess) // handle the error
return;
Task.Run(() =>
{
var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream);
writer.Write("Stack Overflow");
writer.Close();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.SetTitle("test.txt")
.SetMimeType("text/plain")
.Build();
DriveClass.DriveApi
.GetRootFolder(GAClient)
.CreateFile(GAClient, changeSet, contentResults.DriveContents);
});
}
public IDriveContents DriveContents
{
get
{
throw new NotImplementedException();
}
}
public Statuses Status
{
get
{
throw new NotImplementedException();
}
}
public void Dispose()
{
}
Nothing happen after the line DriveClass.DriveApi.NewDriveContents(GAClient).SetResultCallback(this); And the program never goes in OnResult. Is there a OnFailed method that can help me ?

How to create the file inside a folder in google drive?

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)

How to upload a file to google drive folder using android google drive sdk

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/

Drive API for Android: App folder not getting sync

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) {
}
});

Read AppFolder file data in android

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.

Categories

Resources