Java Code Examples for com.google.android.gms.drive.DriveApi#DriveContentsResult

The following examples show how to use com.google.android.gms.drive.DriveApi#DriveContentsResult . 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
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void doRestore(DoDriveRestore event) {
    try {
        ConnectionResult connectionResult = connect();
        if (connectionResult.isSuccess()) {
            DriveFile file = Drive.DriveApi.getFile(googleApiClient, event.selectedDriveFile.driveId);
            DriveApi.DriveContentsResult contentsResult = file.open(googleApiClient, DriveFile.MODE_READ_ONLY, null).await();
            if (contentsResult.getStatus().isSuccess()) {
                DriveContents contents = contentsResult.getDriveContents();
                try {
                    DatabaseImport.createFromGoogleDriveBackup(context, db, contents).importDatabase();
                    bus.post(new DriveRestoreSuccess());
                } finally {
                    contents.discard(googleApiClient);
                }
            } else {
                handleFailure(contentsResult.getStatus());
            }
        } else {
            handleConnectionResult(connectionResult);
        }
    } catch (Exception e) {
        handleError(e);
    }
}
 
Example 2
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 3
Source File: EditContentsAsyncTask.java    From ToDay with MIT License 6 votes vote down vote up
@Override
protected Boolean doInBackgroundConnected(EditContentParams... args) {
    DriveFile file = args[0].getFileToWrite();
    String dataToWrite = args[0].getDataToWrite();

    try {
        DriveApi.DriveContentsResult driveContentsResult = file.open(
                getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
            return false;
        }
        DriveContents driveContents = driveContentsResult.getDriveContents();
        OutputStream outputStream = driveContents.getOutputStream();
        outputStream.write(dataToWrite.getBytes());
        com.google.android.gms.common.api.Status status =
                driveContents.commit(getGoogleApiClient(), null).await();
        return status.getStatus().isSuccess();
    } catch (IOException e) {
        AppUtils.showMessage(context,"Failed to write data to file.");
    }
    return false;
}
 
Example 4
Source File: DriveSyncController.java    From Drive-Database-Sync with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the DriveContentsResult returned from the request to get the DriveFile of the
 * Database.
 * @param result the DriveContentsResult representing the Drive copy of the Database
 */
@Override
public void onFileResultsReady(DriveApi.DriveContentsResult result) {

    if (!mDriveClient.isConnected()) {
        mDriveClient.connect();
    }

    this.result = result;

    int which = deQueue();

    switch (which) {
        case PUT:
            writeLocalDbToCloudStream(result.getDriveContents().getOutputStream());
            result.getDriveContents().commit(mDriveClient, null);
            break;
        case GET:
            writeCloudStreamToLocalDb(result.getDriveContents().getInputStream());
            break;
    }
    if (ongoingRequest) {
        mDriveLayer.getFile(localDb.getName());
    }
}
 
Example 5
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 6
Source File: ActivityUtils.java    From CumulusTV with MIT License 6 votes vote down vote up
public static void createDriveData(Activity activity, GoogleApiClient gapi,
        final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback) {
    PermissionUtils.requestPermissionIfDisabled(activity,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            activity.getString(R.string.permission_storage_rationale));
    if(gapi == null)
        gapi = mCloudStorageProvider.connect(activity);
    try {
        final GoogleApiClient finalGapi = gapi;
        new AlertDialog.Builder(activity)
                .setTitle(R.string.create_sync_file_title)
                .setMessage(R.string.create_sync_file_description)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Drive.DriveApi.newDriveContents(finalGapi)
                                .setResultCallback(driveContentsCallback);
                    }
                })
                .setNegativeButton(R.string.no, null)
                .show();
    } catch(Exception ignored) {
        Toast.makeText(activity, "Error creating drive data: " + ignored.getMessage(),
                Toast.LENGTH_SHORT).show();
    }
}
 
Example 7
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 8
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 9
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 10
Source File: RetrieveDriveFileContentsAsyncTask.java    From faceswap with Apache License 2.0 5 votes vote down vote up
@Override
protected String doInBackgroundConnected(DriveId... params) {
    String state = null;
    DriveFile file = params[0].asDriveFile();
    DriveApi.DriveContentsResult driveContentsResult =
            file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
    if (!driveContentsResult.getStatus().isSuccess()) {
        return null;
    }
    DriveContents driveContents = driveContentsResult.getDriveContents();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(driveContents.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String line;
    try {
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append("\n");
        }
        state = builder.toString();
        reader.close();
    } catch (IOException e) {
        Log.e(TAG, "IOException while reading from the stream", e);
    }
    driveContents.discard(getGoogleApiClient());
    String validState=UIUtils.stripMagicSequence(state);
    return validState;
}
 
Example 11
Source File: DriveLayer.java    From Drive-Database-Sync with Apache License 2.0 5 votes vote down vote up
/**
 * {@link DriveFioResultsCallback} called when a DriveFile I/O operation returns a
 * DriveContentResult. Merely passes the Result up to the {@link FileResultsReadyCallback}
 * registered in this {@link DriveLayer}.
 * @param result the DriveContentResult
 */
@Override
public void onFioResult(DriveApi.DriveContentsResult result) {
    if (debug) {
        Log.d("DriveLayer", "Got Fio result");
    }
    callback.onFileResultsReady(result);
}
 
Example 12
Source File: DriveFio.java    From Drive-Database-Sync with Apache License 2.0 5 votes vote down vote up
/**
 * Results handler for the asynchronous work methods in this class. Triages the Result and then
 * passes it up to the appropriate callback based on the type.
 * @param result the returned result.
 */
@Override
public void onResult(Result result) {
    if (result instanceof DriveApi.DriveContentsResult) {
        callback.onFioResult((DriveApi.DriveContentsResult) result);
    }

    if (result instanceof DriveFolder.DriveFileResult) {
        callback.onFileCreatedResult((DriveFolder.DriveFileResult) result);
    }
}
 
Example 13
Source File: DriveSettingsManager.java    From CumulusTV with MIT License 5 votes vote down vote up
@Override
protected Boolean doInBackground(Object... args) {
    DriveFile file = (DriveFile) args[0];
    String data = (String) args[1];
    try {
        DriveApi.DriveContentsResult driveContentsResult = file.open(
                mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
            return false;
        }
        driveContents = driveContentsResult.getDriveContents();
        OutputStream outputStream = driveContents.getOutputStream();
        outputStream.write(data.getBytes());
        com.google.android.gms.common.api.Status status =
                driveContents.commit(mGoogleApiClient, null).await();
        if(mGoogleDriveListener != null) {
            Handler h = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    mGoogleDriveListener.onActionFinished(false);
                }
            };
            h.sendEmptyMessage(0);
        }
        return status.getStatus().isSuccess();
    } catch (IOException e) {
        if (DEBUG) {
            Log.e(TAG, "IOException while appending to the output stream", e);
        }
    }
    return false;
}
 
Example 14
Source File: DriveFioResultsCallback.java    From Drive-Database-Sync with Apache License 2.0 2 votes vote down vote up
/**
 * Method called when a DriveContentsResult is returned, usually as a result of querying the
 * AppFolder for a Database DriveFile
 * @param result the DriveContentsResult indicating the request status
 */
void onFioResult(DriveApi.DriveContentsResult result);
 
Example 15
Source File: FileResultsReadyCallback.java    From Drive-Database-Sync with Apache License 2.0 2 votes vote down vote up
/**
 * Method called when some DriveContentsResult is ready, indicating results of an attempt to
 * get a reference to the Database DriveFile
 * @param result the DriveContentsResult indicating the status of request
 */
void onFileResultsReady(DriveApi.DriveContentsResult result);