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

The following examples show how to use com.google.android.gms.drive.DriveApi. 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: 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 #3
Source File: Querier.java    From Drive-Database-Sync with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the result of the query. If the results are nonzero, passes up the {@link Metadata}
 * out of the result one at a time through {@link QuerierResultCallback#onQuerierResult(Metadata)}
 * with the {@link QuerierResultCallback} registered in ths {@link Querier}. If the results are
 * null, calls {@link QuerierResultCallback#onNoQuerierResult()}
 * @param result the result of the query
 */
@Override
public void onResult(DriveApi.MetadataBufferResult result) {
    if (!result.getStatus().isSuccess()) {
        Log.e("Querier", "Problem while retrieving files");
        return;
    }

    // Get the metadata buffer
    MetadataBuffer buffer = result.getMetadataBuffer();

    // Check for file dne
    if (buffer.getCount() == 0) {
        // Call null result callback
        callback.onNoQuerierResult();
    }

    // Get the metadata
    for (Metadata m : buffer) {
        if (m.isInAppFolder() && !m.isTrashed()) {
            callback.onQuerierResult(m);
            break;
        }
    }
}
 
Example #4
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 #5
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 #6
Source File: CloudletDemoActivity.java    From faceswap with Apache License 2.0 6 votes vote down vote up
private void readFileFromGoogleDrive(){
    if (mGoogleApiClient !=null && mGoogleApiClient.isConnected()){
        // Let the user pick text file
        // no files selected by the user.
        //http://stackoverflow.com/questions/26331046/android-how-can-i-access-a-spreadsheet-with-the-google-drive-sdk
        // cannot open google doc file
        IntentSender intentSender = Drive.DriveApi
                .newOpenFileActivityBuilder()
                .setMimeType(new String[]{"text/plain", "application/vnd.google-apps.document"})
                .build(mGoogleApiClient);
        try {
            startIntentSenderForResult(intentSender, GDRIVE_REQUEST_CODE_OPENER, null, 0, 0, 0);
        } catch (IntentSender.SendIntentException e) {
            Log.w(TAG, "Unable to send intent", e);
        }
    }
}
 
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: 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 #9
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 #10
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 #11
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@DebugLog
public void readFileContent(final String file_name, final List<Metadata> remainings) {
    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, file_name))
            .build();

    app_folder_for_user.queryChildren(_parent.getClient(), query)
            .setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
                @Override
                public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
                    MetadataBuffer buffer = metadataBufferResult.getMetadataBuffer();
                    int count = buffer.getCount();
                    if (count > 0) {
                        readFileFromDrive(buffer, buffer.get(0).getDriveId());
                    } else {
                        _parent.onFileRead(null);
                    }

                    readFileContent(remainings);
                }
            });
}
 
Example #12
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@DebugLog
private void readFileFromDrive(final MetadataBuffer meta_data, final DriveId drive_id) {
    Drive.DriveApi.getFile(_parent.getClient(), drive_id)
            .open(_parent.getClient(), DriveFile.MODE_READ_ONLY, null)
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
                @Override
                public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
                    try {
                        InputStream input = driveContentsResult.getDriveContents()
                                .getInputStream();
                        String total = consumeStream(input);

                        AmiiboFile amiibo_file = AmiiboFile.fromString(total.toString());
                        _parent.onFileRead(amiibo_file);
                        if (!meta_data.isClosed()) meta_data.release();
                    } catch (IOException e) {
                        e.printStackTrace();
                        _parent.onFileRead(null);
                    }
                }
            });
}
 
Example #13
Source File: SettingsBackup.java    From Slide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onResult(DriveApi.MetadataBufferResult result) {

    int i = 0;
    for (Metadata a : result.getMetadataBuffer()) {
        i++;
        title = a.getTitle();
        new RetrieveDriveFileContentsAsyncTask(title).execute(a.getDriveId());


    }
    progress = new MaterialDialog.Builder(SettingsBackup.this)
            .cancelable(false)
            .title(R.string.backup_restoring)
            .progress(false, i)
            .build();
    progress.show();


}
 
Example #14
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 6 votes vote down vote up
private List<DriveFileInfo> fetchFiles(DriveApi.MetadataBufferResult metadataBufferResult) {
    List<DriveFileInfo> files = new ArrayList<DriveFileInfo>();
    MetadataBuffer metadataBuffer = metadataBufferResult.getMetadataBuffer();
    if (metadataBuffer == null) return files;
    try {
        for (Metadata metadata : metadataBuffer) {
            if (metadata == null) continue;
            String title = metadata.getTitle();
            if (!title.endsWith(".backup")) continue;
            files.add(new DriveFileInfo(metadata.getDriveId(), title, metadata.getCreatedDate()));
        }
    } finally {
        metadataBuffer.close();
    }
    Collections.sort(files);
    return files;
}
 
Example #15
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 5 votes vote down vote up
@DebugLog
private void getAmiiboFolder() {
    Drive.DriveApi.getRootFolder(_parent.getClient())
            .listChildren(_parent.getClient())
            .setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
                @Override
                public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
                    boolean found = false;
                    try {
                        List<Metadata> files = new ArrayList<>();
                        MetadataBuffer buffer = metadataBufferResult.getMetadataBuffer();
                        Metadata data;

                        for (int i = 0; i < buffer.getCount(); i++) {
                            data = buffer.get(i);
                            if (data.getTitle().equals(AMIIBO_FOLDER) && data.isFolder()
                                    && !data.isTrashed()) {
                                app_folder_for_user = Drive.DriveApi
                                        .getFolder(_parent.getClient(), data.getDriveId());
                                Log.d("FileManager", data.getDriveId() + " " + data.getTitle());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (app_folder_for_user != null) {
                        listFiles();
                    } else {
                        createAmiiboFolder();
                    }
                }
            });
}
 
Example #16
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 5 votes vote down vote up
@DebugLog
public void listFiles() {

    if (app_folder_for_user != null) {

        Log.d("FileManager", app_folder_for_user.getDriveId().toString());

        app_folder_for_user.listChildren(_parent.getClient())
                .setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
                    @Override
                    public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
                        List<Metadata> files = new ArrayList<>();
                        MetadataBuffer buffer = metadataBufferResult.getMetadataBuffer();
                        Metadata data;
                        Log.d("FileManager", "onResult " + buffer.getCount() + " " + metadataBufferResult.getStatus().isSuccess());

                        for (int i = 0; i < buffer.getCount(); i++) {
                            data = buffer.get(i);
                            Log.d("FileManager", "data :: " + data.getTitle());
                            if (data.getTitle().endsWith(EXTENSION)) {
                                if (!hasFileLocally(data.getTitle())) {
                                    files.add(data);
                                }
                            }
                        }

                        _parent.onListFilesResult(files);
                    }
                });
    } else {
        getAmiiboFolder();
    }
}
 
Example #17
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 #18
Source File: DriveSettingsManager.java    From CumulusTV with MIT License 5 votes vote down vote up
/**
 * Writes some data to a Google Drive file, this can get from a preference
 * @param driveId The id of the file to be written to
 * @param data The string of data that should be written
 */
public void writeToGoogleDrive(DriveId driveId, String data) {
    DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
    if (DEBUG) {
        Log.d(TAG, "Writing to " + driveId + " -> " + data);
    }
    new EditGoogleDriveAsyncTask(mContext).execute(file, data);
}
 
Example #19
Source File: ActivityUtils.java    From CumulusTV with MIT License 5 votes vote down vote up
public static void syncFile(Activity activity, GoogleApiClient gapi) {
    if (DEBUG) {
    Log.d(TAG, "About to sync a file");
    }
    if (gapi == null && mCloudStorageProvider.connect(activity) != null) {
        gapi = mCloudStorageProvider.connect(activity);
    } else if(mCloudStorageProvider.connect(activity) == null) {
        // Is not existent
        Toast.makeText(activity, "There is no Google Play Service", Toast.LENGTH_SHORT).show();
        return;
    }
    if (gapi.isConnected()) {
        IntentSender intentSender = Drive.DriveApi
                .newOpenFileActivityBuilder()
                .setMimeType(new String[]{"application/json", "text/*"})
                .build(gapi);
        try {
            if (DEBUG) {
                Log.d(TAG, "About to start activity");
            }
            activity.startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0,
                    0);
            if (DEBUG) {
                Log.d(TAG, "Activity activated");
            }
        } catch (IntentSender.SendIntentException e) {
            if (DEBUG) {
                Log.w(TAG, "Unable to send intent", e);
            }
            e.printStackTrace();
        }
    } else {
        Toast.makeText(activity, R.string.toast_msg_wait_google_api_client,
                Toast.LENGTH_SHORT).show();
    }
}
 
Example #20
Source File: DriveActivity.java    From biermacht with Apache License 2.0 5 votes vote down vote up
private void _writeFile() {
  Log.d("DriveActivity", "Writing file to Google Drive.");
  this.action = NONE;
  IntentSender i = Drive.DriveApi
          .newOpenFileActivityBuilder()
          .build(driveClient);

  Drive.DriveApi.newDriveContents(driveClient)
          .setResultCallback(driveContentsCallback);
}
 
Example #21
Source File: DriveActivity.java    From biermacht with Apache License 2.0 5 votes vote down vote up
private void _pickFile() {
  Log.d("DriveActivity", "Starting Google Drive file picker intent");
  this.action = NONE;
  IntentSender i = Drive.DriveApi
          .newOpenFileActivityBuilder()
          .build(driveClient);
  try {
    this.startIntentSenderForResult(i, Constants.REQUEST_DRIVE_FILE_OPEN, null, 0, 0, 0);
  } catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
  }
}
 
Example #22
Source File: DriveLayer.java    From Drive-Database-Sync with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that retrieves the application's AppFolder
 * @return the DriveFolder representing the AppFolder
 */
private DriveFolder getAppFolder() {
    if (debug) {
        Log.d("DriveLayer", "Getting AppFolder");
    }
    return Drive.DriveApi.getAppFolder(mDriveClient);
}
 
Example #23
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 #24
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 #25
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void listFiles(DoDriveListFiles event) {
    try {
        String targetFolder = getDriveFolderName();
        ConnectionResult connectionResult = connect();
        if (connectionResult.isSuccess()) {
            DriveFolder folder = getDriveFolder(targetFolder);
            Query query = new Query.Builder()
                    .addFilter(Filters.and(
                            Filters.eq(SearchableField.MIME_TYPE, Export.BACKUP_MIME_TYPE),
                            Filters.eq(SearchableField.TRASHED, false)
                    ))
                    .build();
            DriveApi.MetadataBufferResult metadataBufferResult = folder.queryChildren(googleApiClient, query).await();
            if (metadataBufferResult.getStatus().isSuccess()) {
                List<DriveFileInfo> driveFiles = fetchFiles(metadataBufferResult);
                handleSuccess(driveFiles);
            } else {
                handleFailure(metadataBufferResult.getStatus());
            }
        } else {
            handleConnectionResult(connectionResult);
        }
    } catch (Exception e) {
        handleError(e);
    }
}
 
Example #26
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private DriveFolder getOrCreateDriveFolder(String targetFolder) throws IOException {
    Query query = new Query.Builder().addFilter(Filters.and(
            Filters.eq(SearchableField.TRASHED, false),
            Filters.eq(SearchableField.TITLE, targetFolder),
            Filters.eq(SearchableField.MIME_TYPE, "application/vnd.google-apps.folder")
    )).build();
    DriveApi.MetadataBufferResult result = Drive.DriveApi.query(googleApiClient, query).await();
    if (result.getStatus().isSuccess()) {
        DriveId driveId = fetchDriveId(result);
        if (driveId != null) {
            return Drive.DriveApi.getFolder(googleApiClient, driveId);
        }
    }
    return createDriveFolder(targetFolder);
}
 
Example #27
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 #28
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 #29
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private DriveId fetchDriveId(DriveApi.MetadataBufferResult result) {
    MetadataBuffer buffer = result.getMetadataBuffer();
    try {
        for (Metadata metadata : buffer) {
            if (metadata == null) continue;
            return metadata.getDriveId();
        }
    } finally {
        buffer.close();
    }
    return null;
}
 
Example #30
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);
}