Creating files

You can create files in two ways with the Drive Android API: using the DriveClient.newCreateFileActivityIntentSender method and the CreateFileActivityOptions class; or using the DriveResourceClient.createFile method. The end result of either approach is the same. However, for instances where the user is specifying the location or title of the file, DriveClient.newCreateFileActivityIntentSender simplifies the process by providing a premade user interface. To create files programmatically or allow users to specify other metadata in a custom UI activity, you must use the createFile() method.

When you create a file through either method, you can specify the initial set of metadata, file contents, and the parent folder. In the case of using DriveClient.newCreateFileActivityIntentSender, the user can subsequently modify the parent folder through the UI.

Creating files with the CreateFileActivityOptions class

The DriveClient.newCreateFileActivityIntentSender method and the CreateFileActivityOptions class provide a convenient way to create new files and allow the user to specify the destination folder and title for the file. You can also use this class to specify the initial metadata and contents for the file.

The class creates an intent that you can use to start the create file activity containing the UI. The following example demonstrates how to use the activity builder to create a text file:

Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
createContentsTask
        .continueWithTask(new Continuation<DriveContents, Task<IntentSender>>() {
            @Override
            public Task<IntentSender> then(@NonNull Task<DriveContents> task)
                    throws Exception {
                DriveContents contents = task.getResult();
                OutputStream outputStream = contents.getOutputStream();
                try (Writer writer = new OutputStreamWriter(outputStream)) {
                    writer.write("Hello World!");
                }

                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                                      .setTitle("New file")
                                                      .setMimeType("text/plain")
                                                      .setStarred(true)
                                                      .build();

                CreateFileActivityOptions createOptions =
                        new CreateFileActivityOptions.Builder()
                                .setInitialDriveContents(contents)
                                .setInitialMetadata(changeSet)
                                .build();
                return getDriveClient().newCreateFileActivityIntentSender(createOptions);
            }
        })
        .addOnSuccessListener(this,
                new OnSuccessListener<IntentSender>() {
                    @Override
                    public void onSuccess(IntentSender intentSender) {
                        try {
                            startIntentSenderForResult(
                                    intentSender, REQUEST_CODE_CREATE_FILE, null, 0, 0, 0);
                        } catch (IntentSender.SendIntentException e) {
                            Log.e(TAG, "Unable to create file", e);
                            showMessage(getString(R.string.file_create_error));
                            finish();
                        }
                    }
                })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            }
        });

Creating files programmatically

To create multiple files programmatically, or if you prefer to use your own UI to let users specify additional metadata, you must use the DriveResourceClient.createFile() method.

When you call DriveResourceClient.createFile(), the Drive for Android API places the new file in the folder that you passed in as an argument. The following example demonstrates creating a new text file in the user's root folder:

final Task<DriveFolder> rootFolderTask = getDriveResourceClient().getRootFolder();
final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
Tasks.whenAll(rootFolderTask, createContentsTask)
        .continueWithTask(new Continuation<Void, Task<DriveFile>>() {
            @Override
            public Task<DriveFile> then(@NonNull Task<Void> task) throws Exception {
                DriveFolder parent = rootFolderTask.getResult();
                DriveContents contents = createContentsTask.getResult();
                OutputStream outputStream = contents.getOutputStream();
                try (Writer writer = new OutputStreamWriter(outputStream)) {
                    writer.write("Hello World!");
                }

                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                                      .setTitle("HelloWorld.txt")
                                                      .setMimeType("text/plain")
                                                      .setStarred(true)
                                                      .build();

                return getDriveResourceClient().createFile(parent, changeSet, contents);
            }
        })
        .addOnSuccessListener(this,
                new OnSuccessListener<DriveFile>() {
                    @Override
                    public void onSuccess(DriveFile driveFile) {
                        showMessage(getString(R.string.file_created,
                                driveFile.getDriveId().encodeToString()));
                        finish();
                    }
                })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            }
        });

Creating empty files

You may sometimes need to create empty files, for example, a user preference file that is empty until the user defines some application property or a plain text file that is empty until some content is written to it later on.

If you are using the DriveClient.newCreateFileActivityIntentSender method and the CreateFileActivityOptions class to create an empty file, pass null in place of DriveContents to the setInitialContents method.

If you are creating empty files programmatically, pass null in place of DriveContents to the createFile method:

getDriveResourceClient()
        .getRootFolder()
        .continueWithTask(new Continuation<DriveFolder, Task<DriveFile>>() {
            @Override
            public Task<DriveFile> then(@NonNull Task<DriveFolder> task) throws Exception {
                DriveFolder parentFolder = task.getResult();
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                                      .setTitle("New file")
                                                      .setMimeType("text/plain")
                                                      .setStarred(true)
                                                      .build();
                return getDriveResourceClient().createFile(parentFolder, changeSet, null);
            }
        })
        .addOnSuccessListener(this,
                new OnSuccessListener<DriveFile>() {
                    @Override
                    public void onSuccess(DriveFile driveFile) {
                        showMessage(getString(R.string.file_created,
                                driveFile.getDriveId().encodeToString()));
                        finish();
                    }
                })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            }
        });

Enviar comentarios sobre…

Drive API for Android
Drive API for Android