com.google.android.gms.drive.MetadataChangeSet Java Examples

The following examples show how to use com.google.android.gms.drive.MetadataChangeSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 6 votes vote down vote up
private Status createFile(DriveFolder folder, String fileName, byte[] bytes) throws IOException {
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle(fileName)
            .setMimeType(Export.BACKUP_MIME_TYPE).build();
    // Create a file in the root folder
    DriveApi.DriveContentsResult contentsResult = Drive.DriveApi.newDriveContents(googleApiClient).await();
    Status contentsResultStatus = contentsResult.getStatus();
    if (contentsResultStatus.isSuccess()) {
        DriveContents contents = contentsResult.getDriveContents();
        contents.getOutputStream().write(bytes);
        DriveFolder.DriveFileResult fileResult = folder.createFile(googleApiClient, changeSet, contents).await();
        return fileResult.getStatus();
    } else {
        return contentsResultStatus;
    }
}
 
Example #2
Source File: CreateFolderInFolderActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void createFolderInFolder(final DriveFolder parent) {
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .setTitle("New folder")
                                          .setMimeType(DriveFolder.MIME_TYPE)
                                          .setStarred(true)
                                          .build();

    getDriveResourceClient()
            .createFolder(parent, changeSet)
            .addOnSuccessListener(this,
                    driveFolder -> {
                        showMessage(getString(R.string.file_created,
                                driveFolder.getDriveId().encodeToString()));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            });
}
 
Example #3
Source File: EditMetadataActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void editMetadata(DriveFile file) {
    // [START drive_android_update_metadata]
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .setStarred(true)
                                          .setIndexableText("Description about the file")
                                          .setTitle("A new title")
                                          .build();
    Task<Metadata> updateMetadataTask =
            getDriveResourceClient().updateMetadata(file, changeSet);
    updateMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.metadata_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_update_metadata]
}
 
Example #4
Source File: DeleteCustomPropertyActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void deleteCustomProperty(DriveFile file) {
    // [START drive_android_delete_custom_property]
    CustomPropertyKey approvalPropertyKey =
            new CustomPropertyKey("approved", CustomPropertyKey.PUBLIC);
    CustomPropertyKey submitPropertyKey =
            new CustomPropertyKey("submitted", CustomPropertyKey.PUBLIC);
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .deleteCustomProperty(approvalPropertyKey)
                                          .deleteCustomProperty(submitPropertyKey)
                                          .build();
    Task<Metadata> updateMetadataTask =
            getDriveResourceClient().updateMetadata(file, changeSet);
    updateMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.custom_property_deleted));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_delete_custom_property]
}
 
Example #5
Source File: CreateEmptyFileActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void createEmptyFile() {
    // [START drive_android_create_empty_file]
    getDriveResourceClient()
            .getRootFolder()
            .continueWithTask(task -> {
                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,
                    driveFile -> {
                        showMessage(getString(R.string.file_created,
                                driveFile.getDriveId().encodeToString()));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            });
    // [END drive_android_create_empty_file]
}
 
Example #6
Source File: CreateFileInFolderActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void createFileInFolder(final DriveFolder parent) {
    getDriveResourceClient()
            .createContents()
            .continueWithTask(task -> {
                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();

                return getDriveResourceClient().createFile(parent, changeSet, contents);
            })
            .addOnSuccessListener(this,
                    driveFile -> showMessage(getString(R.string.file_created,
                            driveFile.getDriveId().encodeToString())))
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
            });
}
 
Example #7
Source File: InsertUpdateCustomPropertyActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void updateCustomProperty(DriveFile file) {
    // [START drive_android_update_custom_property]
    CustomPropertyKey approvalPropertyKey =
            new CustomPropertyKey("approved", CustomPropertyKey.PUBLIC);
    CustomPropertyKey submitPropertyKey =
            new CustomPropertyKey("submitted", CustomPropertyKey.PUBLIC);
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .setCustomProperty(approvalPropertyKey, "yes")
                                          .setCustomProperty(submitPropertyKey, "no")
                                          .build();
    Task<Metadata> updateMetadataTask =
            getDriveResourceClient().updateMetadata(file, changeSet);
    updateMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.custom_property_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_update_custom_property]
}
 
Example #8
Source File: CreateFolderActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void createFolder() {
    getDriveResourceClient()
            .getRootFolder()
            .continueWithTask(task -> {
                DriveFolder parentFolder = task.getResult();
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                                      .setTitle("New folder")
                                                      .setMimeType(DriveFolder.MIME_TYPE)
                                                      .setStarred(true)
                                                      .build();
                return getDriveResourceClient().createFolder(parentFolder, changeSet);
            })
            .addOnSuccessListener(this,
                    driveFolder -> {
                        showMessage(getString(R.string.file_created,
                                driveFolder.getDriveId().encodeToString()));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            });
}
 
Example #9
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@DebugLog
private void createAmiiboFolder() {
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle(AMIIBO_FOLDER).build();

    Drive.DriveApi.getRootFolder(_parent.getClient())
            .createFolder(_parent.getClient(), changeSet)
            .setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
                @Override
                public void onResult(DriveFolder.DriveFolderResult driveFolderResult) {
                    if (driveFolderResult.getStatus().isSuccess()) {
                        app_folder_for_user = driveFolderResult.getDriveFolder();
                        listFiles();
                    } else {
                        app_folder_for_user = null;
                        _parent.onPushFinished();
                    }
                }
            });
}
 
Example #10
Source File: MainActivity.java    From CumulusTV with MIT License 6 votes vote down vote up
@Override
public void onResult(DriveApi.DriveContentsResult result) {
    MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
            .setTitle("cumulustv_channels.json")
            .setDescription("JSON list of channels that can be imported using " +
                    "CumulusTV to view live streams")
            .setMimeType("application/json").build();
    IntentSender intentSender = Drive.DriveApi
            .newCreateFileActivityBuilder()
            .setActivityTitle("cumulustv_channels.json")
            .setInitialMetadata(metadataChangeSet)
            .setInitialDriveContents(result.getDriveContents())
            .build(CloudStorageProvider.getInstance().getClient());
    try {
        startIntentSenderForResult(
                intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        Log.w(TAG, "Unable to send intent", e);
    }
}
 
Example #11
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void createElement(final TGBrowserCallBack<TGBrowserElement> cb, final String name) {
	try {
		MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(name).build();
		
		this.folder.getFolder().createFile(this.client, changeSet, null).setResultCallback(new ResultCallback<DriveFileResult>() {
			public void onResult(DriveFileResult result) {
				if( result.getStatus().isSuccess() ) {
					cb.onSuccess(new TGDriveBrowserFile(TGDriveBrowser.this.folder, result.getDriveFile(), name));
				} else {
					cb.handleError(new TGBrowserException(findActivity().getString(R.string.gdrive_create_file_error)));
				}
			}
		});
	} catch (RuntimeException e) {
		cb.handleError(e);
	}
}
 
Example #12
Source File: LeanbackFragment.java    From CumulusTV with MIT License 6 votes vote down vote up
@Override
public void onResult(DriveApi.DriveContentsResult result) {
    MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
            .setTitle("cumulustv_channels.json")
            .setDescription("JSON list of channels that can be imported using CumulusTV to view live streams")
            .setMimeType("application/json").build();
    IntentSender intentSender = Drive.DriveApi
            .newCreateFileActivityBuilder()
            .setActivityTitle("cumulustv_channels.json")
            .setInitialMetadata(metadataChangeSet)
            .setInitialDriveContents(result.getDriveContents())
            .build(CloudStorageProvider.getInstance().getClient());
    try {
        mActivity.startIntentSenderForResult(
                intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        Log.w(TAG, "Unable to send intent", e);
    }
}
 
Example #13
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private Task<DriveFile> createNewFile() {
    Log.d(TAG, "Creating new grocery list.");
    return getDriveResourceClient().getRootFolder().continueWithTask(
            task -> {
                DriveFolder folder = task.getResult();
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                                      .setTitle(getResources().getString(
                                                              R.string.groceryListFileName))
                                                      .setMimeType("text/plain")
                                                      .build();

                return getDriveResourceClient().createFile(folder, changeSet, null);
            });
}
 
Example #14
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 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, Bitmap image) {
  Log.i(TAG, "New contents created.");
  // Get an output stream for the contents.
  OutputStream outputStream = driveContents.getOutputStream();
  // Write the bitmap data from it.
  ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
  try {
    outputStream.write(bitmapStream.toByteArray());
  } catch (IOException e) {
    Log.w(TAG, "Unable to write file contents.", e);
  }

  // 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("image/jpeg")
          .setTitle("Android Photo.png")
          .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(
              task -> {
                startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0);
                return null;
              });
}
 
Example #15
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an empty folder in the current folder.
 */
private void createFolder() {
    setUiInteractionsEnabled(false);
    int fileCount = mFileFolderAdapter.getCount();
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle("sample folder " + (fileCount + 1))
            .build();
    DriveFolder driveFolder = mNavigationPath.peek().asDriveFolder();
    Task<DriveFolder> createFolderTask =
            mDriveResourceClient.createFolder(driveFolder, changeSet);
    Task<Void> updateTask = updateUiAfterTask(createFolderTask);
    handleTaskError(updateTask, R.string.unexpected_error);
}
 
Example #16
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an empty file in the current folder.
 */
private void createFile() {
    setUiInteractionsEnabled(false);
    int fileCount = mFileFolderAdapter.getCount();
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle("sample file " + (fileCount + 1))
            .setMimeType("text/plain")
            .build();
    DriveFolder driveFolder = mNavigationPath.peek().asDriveFolder();
    Task<DriveFile> createFileTask =
            mDriveResourceClient.createFile(driveFolder, changeSet, null);
    Task<Void> updateTask = updateUiAfterTask(createFileTask);
    handleTaskError(updateTask, R.string.unexpected_error);
}
 
Example #17
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private DriveFolder createDriveFolder(String targetFolder) {
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle(targetFolder).build();
    DriveFolder.DriveFolderResult result = Drive.DriveApi.getRootFolder(googleApiClient).createFolder(googleApiClient, changeSet).await();
    if (result.getStatus().isSuccess()) {
        return result.getDriveFolder();
    } else {
        return null;
    }
}
 
Example #18
Source File: SubscribeChangeEventsForFilesActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onTick(long l) {
    Log.d(TAG, "Updating metadata.");
    MetadataChangeSet metadata =
            new MetadataChangeSet.Builder().setLastViewedByMeDate(new Date()).build();
    getDriveResourceClient()
            .updateMetadata(mSelectedFileId.asDriveResource(), metadata)
            .addOnSuccessListener(SubscribeChangeEventsForFilesActivity.this,
                    metadata1 -> Log.d(TAG, "Updated metadata."))
            .addOnFailureListener(
                    SubscribeChangeEventsForFilesActivity.this, e -> Log.e(TAG, "Unable to update metadata", e));
}
 
Example #19
Source File: ListenChangeEventsForFilesActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onTick(long l) {
    Log.d(TAG, "Updating metadata.");
    MetadataChangeSet metadata =
            new MetadataChangeSet.Builder().setLastViewedByMeDate(new Date()).build();
    getDriveResourceClient()
            .updateMetadata(mSelectedFileId.asDriveResource(), metadata)
            .addOnSuccessListener(ListenChangeEventsForFilesActivity.this,
                    metadata1 -> Log.d(TAG, "Updated metadata."))
            .addOnFailureListener(
                    ListenChangeEventsForFilesActivity.this, e -> Log.e(TAG, "Unable to update metadata", e));
}
 
Example #20
Source File: CreateFileInAppFolderActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void createFileInAppFolder() {
    final Task<DriveFolder> appFolderTask = getDriveResourceClient().getAppFolder();
    final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
    Tasks.whenAll(appFolderTask, createContentsTask)
            .continueWithTask(task -> {
                DriveFolder parent = appFolderTask.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("New file")
                                                      .setMimeType("text/plain")
                                                      .setStarred(true)
                                                      .build();

                return getDriveResourceClient().createFile(parent, changeSet, contents);
            })
            .addOnSuccessListener(this,
                    driveFile -> {
                        showMessage(getString(R.string.file_created,
                                driveFile.getDriveId().encodeToString()));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            });
}
 
Example #21
Source File: TheHubActivity.java    From ToDay with MIT License 5 votes vote down vote up
private void createNewDriveFile() {

        final ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new
                ResultCallback<DriveApi.DriveContentsResult>() {
                    @Override
                    public void onResult(DriveApi.DriveContentsResult result) {
                        if (!result.getStatus().isSuccess()) {
                            Toast.makeText(TheHubActivity.this, R.string.export_failed_msg, Toast.LENGTH_LONG).show();
                            return;
                        }

                        MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                .setMimeType("text/html").build();
//                        IntentSender intentSender = Drive.DriveApi
//                                .newCreateFileActivityBuilder()
//                                .setInitialMetadata(metadataChangeSet)
//                                .setInitialDriveContents(result.getDriveContents())
//                                .build(mGoogleApiClient);
//                        try {
//                            startIntentSenderForResult(intentSender,
//                                    AppConstants.EXPORT_CREATOR_REQUEST_CODE, null, 0, 0, 0);
//                        } catch (IntentSender.SendIntentException e) {
//                            AppUtils.showMessage(TheHubActivity.this, "Data could not be exported");
//                        }
                    }
                };

//        Drive.DriveApi.newDriveContents(mGoogleApiClient)
//                .setResultCallback(contentsCallback);
    }
 
Example #22
Source File: CreateFileActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void createFile() {
    // [START drive_android_create_file]
    final Task<DriveFolder> rootFolderTask = getDriveResourceClient().getRootFolder();
    final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
    Tasks.whenAll(rootFolderTask, createContentsTask)
            .continueWithTask(task -> {
                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,
                    driveFile -> {
                        showMessage(getString(R.string.file_created,
                                driveFile.getDriveId().encodeToString()));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            });
    // [END drive_android_create_file]
}
 
Example #23
Source File: GoogleDriveService.java    From WheelLogAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onResult(@NonNull DriveApi.DriveContentsResult result) {
    if (!result.getStatus().isSuccess()) {
        Timber.i("Error while trying to create new file contents");
        exitUploadFailed();
        return;
    }
    final DriveContents driveContents = result.getDriveContents();

    updateNotification("Uploading file " + file.getName());
    // write content to DriveContents
    OutputStream outputStream = driveContents.getOutputStream();
    Writer writer = new OutputStreamWriter(outputStream);

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null)
            writer.append(line).append('\r');

        br.close();
        writer.close();
    } catch (IOException e) {
        Timber.e(e.getMessage());
    }

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

    // create a file in "WheelLog Logs" folder
    folderDriveId.asDriveFolder()
        .createFile(getGoogleApiClient(), changeSet, driveContents)
                    .setResultCallback(fileCreatedCallback);
}
 
Example #24
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
private Task<Void> createFileIntentSender(DriveContents driveContents) {

        final String inFileName = activity.getDatabasePath(DATABASE_NAME).toString();

        try {
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);
            OutputStream outputStream = driveContents.getOutputStream();

            // Transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                .setTitle("database_backup.db")
                .setMimeType("application/db")
                .build();


        CreateFileActivityOptions createFileActivityOptions =
                new CreateFileActivityOptions.Builder()
                        .setInitialMetadata(metadataChangeSet)
                        .setInitialDriveContents(driveContents)
                        .build();

        return mDriveClient
                .newCreateFileActivityIntentSender(createFileActivityOptions)
                .continueWith(
                        task -> {
                            activity.startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATION, null, 0, 0, 0);
                            return null;
                        });
    }
 
Example #25
Source File: DriveFio.java    From Drive-Database-Sync with Apache License 2.0 5 votes vote down vote up
/**
 * Work method to create a DriveFile within the passed params. Sets the result callback to this,
 * which calls {@link #onResult(Result)}
 * @param driveClient the {@link GoogleApiClient} to use for this Drive request
 * @param driveFolder the {@link DriveFolder} to create the DriveFile in
 * @param filename the filename for the to-be-created {@link DriveFile}
 */
public void createFile(GoogleApiClient driveClient, DriveFolder driveFolder, String filename) {

    MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
            .setTitle(filename)
            .build();

    driveFolder.createFile(driveClient, metadataChangeSet, null).setResultCallback(this);
}
 
Example #26
Source File: PinFileActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void pinFile(final DriveFile file) {
    // [START drive_android_pin_file]
    Task<Metadata> pinFileTask = getDriveResourceClient().getMetadata(file).continueWithTask(
            task -> {
                Metadata metadata = task.getResult();
                if (!metadata.isPinnable()) {
                    showMessage(getString(R.string.file_not_pinnable));
                    return Tasks.forResult(metadata);
                }
                if (metadata.isPinned()) {
                    showMessage(getString(R.string.file_already_pinned));
                    return Tasks.forResult(metadata);
                }
                MetadataChangeSet changeSet =
                        new MetadataChangeSet.Builder().setPinned(true).build();
                return getDriveResourceClient().updateMetadata(file, changeSet);
            });
    // [END drive_android_pin_file]
    // [START drive_android_pin_file_completion]
    pinFileTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.metadata_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_pin_file_completion]
}
 
Example #27
Source File: MainActivity.java    From drive-android-quickstart with Apache License 2.0 5 votes vote down vote up
/**
 * 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, Bitmap image) {
  Log.i(TAG, "New contents created.");
  // Get an output stream for the contents.
  OutputStream outputStream = driveContents.getOutputStream();
  // Write the bitmap data from it.
  ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
  try {
    outputStream.write(bitmapStream.toByteArray());
  } catch (IOException e) {
    Log.w(TAG, "Unable to write file contents.", e);
  }

  // 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("image/jpeg")
          .setTitle("Android Photo.png")
          .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;
            }
          });
}
 
Example #28
Source File: DriveSyncService.java    From Passbook with Apache License 2.0 5 votes vote down vote up
@Override
public void send(byte[] data) {
    if(data != null) {
        mData = data;
        if (mDriveResourceClient == null) {
            mListener.onSyncFailed(CA.AUTH);
            return;
        }
        Task<DriveContents> contentsTask;
        if (mDriveId == null) {
            contentsTask = mDriveResourceClient.getAppFolder()
                    .continueWithTask(t -> {
                        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                .setTitle(SAVED_DATA)
                                .setMimeType("application/bin")
                                .build();
                        DriveFile file = mDriveResourceClient.createFile(t.getResult(), changeSet, null).getResult();
                        mDriveId = file.getDriveId();
                        return mDriveResourceClient.openFile(file, DriveFile.MODE_WRITE_ONLY);
                    });
        } else {
            contentsTask = mDriveResourceClient.openFile(mDriveId.asDriveFile(), DriveFile.MODE_WRITE_ONLY);
        }
        contentsTask
                .continueWithTask(t -> {
                    DriveContents contents = t.getResult();
                    OutputStream outputStream = contents.getOutputStream();
                    outputStream.write(mData);
                    return mDriveResourceClient.commitContents(contents, null);
                })
                .addOnFailureListener(e -> mListener.onSyncFailed(CA.DATA_SENT))
                .addOnSuccessListener(s -> mListener.onSyncProgress(CA.DATA_SENT));
    }
}
 
Example #29
Source File: CreateFileWithCreatorActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
private void createFileWithIntent() {
    // [START drive_android_create_file_with_intent]
    Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
    createContentsTask
            .continueWithTask(task -> {
                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,
                    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, e -> {
                Log.e(TAG, "Unable to create file", e);
                showMessage(getString(R.string.file_create_error));
                finish();
            });
    // [END drive_android_create_file_with_intent]
}
 
Example #30
Source File: AppendContentsActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
private void appendContents(DriveFile file) {
    // [START drive_android_open_for_append]
    Task<DriveContents> openTask =
            getDriveResourceClient().openFile(file, DriveFile.MODE_READ_WRITE);
    // [END drive_android_open_for_append]
    // [START drive_android_append_contents]
    openTask.continueWithTask(task -> {
        DriveContents driveContents = task.getResult();
        ParcelFileDescriptor pfd = driveContents.getParcelFileDescriptor();
        long bytesToSkip = pfd.getStatSize();
        try (InputStream in = new FileInputStream(pfd.getFileDescriptor())) {
            // Skip to end of file
            while (bytesToSkip > 0) {
                long skipped = in.skip(bytesToSkip);
                bytesToSkip -= skipped;
            }
        }
        try (OutputStream out = new FileOutputStream(pfd.getFileDescriptor())) {
            out.write("Hello world".getBytes());
        }
        // [START drive_android_commit_contents_with_metadata]
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                              .setStarred(true)
                                              .setLastViewedByMeDate(new Date())
                                              .build();
        Task<Void> commitTask =
                getDriveResourceClient().commitContents(driveContents, changeSet);
        // [END drive_android_commit_contents_with_metadata]
        return commitTask;
    })
        .addOnSuccessListener(this,
                aVoid -> {
                    showMessage(getString(R.string.content_updated));
                    finish();
                })
        .addOnFailureListener(this, e -> {
            Log.e(TAG, "Unable to update contents", e);
            showMessage(getString(R.string.content_update_failed));
            finish();
        });
    // [END drive_android_append_contents]
}