Search code examples
google-drive-android-api

Google Drive Android SDK can't write to App Folder


I would like to save my app data in Google Drive to share it between Devices of the User.

First if there is no file i create one in google Drive:

Drive.DriveApi.getAppFolder(driveApiClient)
            .createFile(driveApiClient, changeSet, null)

In the callback i open the file:

driveFileResult.getDriveFile().open(driveApiClient, DriveFile.MODE_WRITE_ONLY, null)

And in that Callback i write to the File as described https://developers.google.com/drive/android/files#making_modifications:

DriveContents contents = driveContentsResult.getDriveContents();
try {
     ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();

     FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
                    .getFileDescriptor());
     Writer writer = new OutputStreamWriter(fileOutputStream);
     writer.write("hello world");
} catch (IOException e) {
     e.printStackTrace();
}

contents.commit(driveApiClient, null, new ExecutionOptions.Builder().setConflictStrategy(ExecutionOptions.CONFLICT_STRATEGY_OVERWRITE_REMOTE).build())

In the status callback of the commit i get a success.

Next time i open the file the file is empty, and the size in the metadata is 0.

What am i doing wrong?


Solution

  • Just did a quick test. Definitely close the OutputStreamWriter - writer.close() before the commit; otherwise, you will get an empty file.