android


Create or Open native Google documents using GoogleDriveApi


I have been closely following the documentation for the Google Drive Android API and, all works great. I can create new text documents and read them back in using the mime type of text/plain.
What I cannot do is create a native Google "Document" or "Spreadsheet." Actually, I can create them by using the mime type to application/vnd.google-apps.document or application/vnd.google-apps.spreadsheet as per Supported MIME Types documentation.
If, however, I try to write content to these documents, the documents never get uploaded.
If I try to read documents that have content (content I created via a web browser) my openContents call fails.
Again, I can create text/plain documents and write to them, but they are not native Google Documents. I have scowered the documentation and sample files, but nothing describes what I'm looking for.
This seems so basic. Does the new GoogleApiClient not support doing this? What am I missing or doing wrong?
Here is the core code for creating. I have a similar issue when trying to read a application/vnd.google-apps.document but I'm sure the two issues are related. I'll spare the verbosity of "read" code.
private void exportToGDriveFile() {
Drive.DriveApi.newContents(getGoogleApiClient()).setResultCallback(createNewFileCallback);
}
final private ResultCallback<ContentsResult> createNewFileCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
writeLog("Error while trying to create new file contents");
return;
}
String fileName = getIncrementedFileName();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(fileName)
.setMimeType("text/plain") // <-- This works! I can write and read back :)
//.setMimeType("application/vnd.google-apps.document") <-- can create if no contents are included.
//.setMimeType("application/vnd.google-apps.spreadsheet")
.setStarred(true)
.build();
writeLog("creating file: " + fileName);
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.setResultCallback(afterCreateFileCallback);
}
};
private ResultCallback<DriveFileResult> afterCreateFileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
writeLog("Error while trying to create the file");
return;
}
DriveFile driveFile = result.getDriveFile();
writeLog("Created file " + driveFile.getDriveId());
new WriteFileAsyncTask().execute(driveFile);
}
};
private class WriteFileAsyncTask extends AsyncTask<DriveFile, Void, Boolean> {
#Override
protected Boolean doInBackground(DriveFile... args) {
DriveFile file = args[0];
try {
ContentsResult contentsResult = file.openContents(getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
if (!contentsResult.getStatus().isSuccess()) {
return false;
}
/************************
If I try to write content here, `application/vnd.google-apps.document` files will not upload.
*************************/
String contents = "Hello World";
OutputStream outputStream = contentsResult.getContents().getOutputStream();
outputStream.write(contents.getBytes());
com.google.android.gms.common.api.Status status = file.commitAndCloseContents(
getGoogleApiClient(), contentsResult.getContents()).await();
return status.getStatus().isSuccess();
} catch (IOException e) {
// toast("IOException while appending to the output stream");
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
// toast("Error while editing contents");
return;
}
// toast("Successfully uploaded Quizifications!");
}
}
It's not currently possible to read or edit the contents of Google Documents, Spreadsheets or Presentation files. They files are of a special type that don't have standard binary content, so you can't read and write from them in the same way you can from other files.
You can, however, interact with the metadata of existing files.
Sorry for the confusion, we should update the behavior so that its clear that its not possible.
Updating Google Docs with HTML is simple. Just make an api request with html-formatted text in the body (html tag is required) and content-type to be google docs, then your created/updated file will be available to the user as a Google Doc with all the formatting options.
request({
uri: 'https://www.googleapis.com/upload/drive/v2/files/'+fileId,
method: 'PUT',
qs: {
uploadType: 'media'
},
form: '<html> Hello <b>World!</b> </html>',
headers: {
'Content-Type': 'application/vnd.google-apps.document',
'Authorization': 'Bearer ' + access_token
}}, function (error, response, body){
})

Related Links

Picking an Image File From an External SD Card (USB OTG Storage)
Why do SearchView and android.support.v7.widget.SearchView not focus anymore
RxJava: return a cached value synchronously/immediately
How to check for string changes after a user presses a Button?
android - groovy script error in custom live template
How to zoom in an ImageView in Android
How to load string.xml for indian languages in android?
Classic asp or phonegap
Android WhisperSystems/libsignal-service
android retrofit await method to finish outside of response
Unable to restore array to array adapter when addTextChangedListener is used
Detect if first auth via Facebook/Google
Install error when trying to update android application programmatically [duplicate]
Android the navigation toolbar icon and logo can not align
Reverse image on Nexus 5x in portrait
Android Studio 2.3, cannot build gradle. Error 304 [duplicate]

Categories

HOME
shell
scikit-learn
cheerio
pda
components
pclxl
ms-access-2016
cublas
cq5
nested-if
google-cloud-datalab
nstableheaderview
openstreetmap
why3
symmetricds
event-sourcing
symfony-2.8
job-scheduling
microsoft-dynamics-nav
android-7.0-nougat
xmonad
google-container-registry
digital-signature
gmm
sencha-touch
sar
google-maps-autocomplete
springfox
backpack-for-laravel
monit
jboss6.x
mount
xcode-ui-testing
shared
sqlpackage
scrollview
jmockit
r-grid
erb
imagenet
ideascript
sessionstorage
nohup
node-mssql
diacritics
magento-1.9.3
postgresql-8.4
softmax
microsoft-metro
file-sharing
show-hide
servermanager
fwrite
sonarlint-eclipse
datamaps
posixct
yii2-user
flyout
cmp
swingworker
rxtx
donations
materialized-path-pattern
omxplayer
pacemaker
xcode-server
async.js
mta
dup
firebase-security
stream-processing
deep
nss
phpwebsocket
cortex-m
nupic
libav
rasterize
relativelayout
concurrentmodification
oracle-spatial
zen-cart
canalyzer
iced-coffeescript
mirror
teamcity-9.1
code-documentation
apache-spark-1.3
packet-sniffers
easyrtc
iso-prolog
trdion2011
unix-socket
kissfft
sbcl
gd-graph
tlf
nevron
flex++
cascadingdropdown
android-sdk-2.3
garbage
subproject
josql
jsr286
urlrewriter
cuteeditor
socketserver
nhprof
timertask
non-clustered-index
dot-emacs
message-passing
windows-identity
fault-tolerance
linfu-dynamicproxy
xslcompiledtransform
contentpresenter
commercial-application

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App