1

Investigando respecto a la API de google drive, encontré este ejemplo que en teoría me permite subir una imagen a drive. El problema que tengo es que el siguiente código:

File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
        .setFields("id")
        .execute();
System.out.println("File ID: " + file.getId());

Del cual, no me reconoce la librería FileContent, File me pide una sobrecarga, y no entiendo que es lo que estoy haciendo mal.

¿Alguien podría explicarme que me falta?

1

2 respuestas 2

2

Actualización:

Se debe migrar a la API : Google Drive API

Sinceramente veo tu ejemplo y no me parece que funcione, en realidad se necesita un Bitmap para agregar mediante el dialogo de Google Drive

Este es un método el cual recibe el bitmap de la imagen para ser agregado a Google Drive:

    //Create a new file and save it to Drive.
   private void saveFileToDrive(Bitmap image) {
    // Start by creating a new contents, and setting a callback.
    Log.i(TAG, "saveFileToDrive() Creating new content.");
    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveContentsResult>() {
                @Override
                public void onResult(DriveContentsResult result) {
                    // If the operation wasn't successful, return
                    if (!result.getStatus().isSuccess()) {
                        Log.e(TAG, "Failed to create new content!.");
                        return;
                    }
                    Log.i(TAG, "New content has been created.");
                    // Get an output stream for the contents.
                    OutputStream outputStream = result.getDriveContents().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 e1) {
                        Log.i(TAG, "Unable to write file contents.");
                    }
                    // 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("myPhoto.png").build();
                    // Create an intent for the file chooser, and start it.
                    IntentSender intentSender = Drive.DriveApi
                            .newCreateFileActivityBuilder()
                            .setInitialMetadata(metadataChangeSet)
                            .setInitialDriveContents(result.getDriveContents())
                            .build(mGoogleApiClient);
                    try {
                        startIntentSenderForResult(
                                intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                    } catch (SendIntentException e) {
                        Log.i(TAG, "Failed to launch file chooser.");
                    }
                }
            });
}

Revisa este ejemplo que hace uso de la camara para obtener el bitmap de la imagen para posteriormente subir a Google Drive.

introducir la descripción de la imagen aquí introducir la descripción de la imagen aquí

2
1

Debes usar la API específica para Android, como indica Google. Sea mediante la clase CreateFileActivityBuilder o mediante el método createFile() de DriveFolder

Este es el ejemplo oficial de Google para Android, en el cual puedes inspirarte para crear archivos en Drive. En ese mismo repositorio de Github hay otros ejemplos, en la carpeta Demo.

Fuente: Google (Github)

import android.os.Bundle;

import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.MetadataChangeSet;

import java.lang.Override;


/**
 * An activity to create a file inside a folder.
 */
public class CreateFileInFolderActivity extends BaseDemoActivity {

    private DriveId mFolderDriveId;

    @Override
    public void onConnected(Bundle connectionHint) {
        super.onConnected(connectionHint);
        Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FOLDER_ID)
                .setResultCallback(idCallback);
    }

    final private ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
        @Override
        public void onResult(DriveIdResult result) {
            if (!result.getStatus().isSuccess()) {
                showMessage("Cannot find DriveId. Are you authorized to view this file?");
                return;
            }
            mFolderDriveId = result.getDriveId();
            Drive.DriveApi.newDriveContents(getGoogleApiClient())
                    .setResultCallback(driveContentsCallback);
        }
    };

    final private ResultCallback<DriveContentsResult> driveContentsCallback =
            new ResultCallback<DriveContentsResult>() {
        @Override
        public void onResult(DriveContentsResult result) {
            if (!result.getStatus().isSuccess()) {
                showMessage("Error while trying to create new file contents");
                return;
            }
            DriveFolder folder = mFolderDriveId.asDriveFolder();
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle("New file")
                    .setMimeType("text/plain")
                    .setStarred(true).build();
            folder.createFile(getGoogleApiClient(), changeSet, result.getDriveContents())
                    .setResultCallback(fileCallback);
        }
    };

    final private ResultCallback<DriveFileResult> fileCallback =
            new ResultCallback<DriveFileResult>() {
        @Override
        public void onResult(DriveFileResult result) {
            if (!result.getStatus().isSuccess()) {
                showMessage("Error while trying to create the file");
                return;
            }
            showMessage("Created a file: " + result.getDriveFile().getDriveId());
        }
    };
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.