获取result.getDriveFolder()。getDriveId()。getResourceId()始终为null

时间:2016-05-07 14:30:11

标签: android google-play-services google-drive-android-api

尝试将所有文​​件放在文件夹中但获取result.getDriveFolder()。getDriveId()。getResourceId()始终为null。我搜索并找到了一些链接,我尝试使用此链接enter link description here

中提到的步骤

这是我的代码: -

  public class MainActivity extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener {
    public ArrayList songsList = new ArrayList();
    private static final String TAG = "drive-quickstart";
    private GoogleApiClient mGoogleApiClient;
    public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
    protected static final int REQUEST_CODE_RESOLUTION = 1;
    protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
    private DriveId mFolderDriveId;
    public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
    public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";

    /**
     * Extra for account name.
     */
    protected static final String EXTRA_ACCOUNT_NAME = "account_name";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final File mainDir = new File(Environment.getExternalStorageDirectory()
                .getPath());
        loadSdcardfiles(mainDir);
    }

    /**
     * Create a new file and save it to Drive.
     */

    private void saveFileToDrive(final File file) {
        Log.i(TAG, "Creating new contents.");
        Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
                new ResultCallback<DriveApi.DriveContentsResult>() {

                    @Override
                    public void onResult(DriveApi.DriveContentsResult result) {
                        if (!result.getStatus().isSuccess()) {
                            Log.i(TAG, "Failed to create new contents.");
                            return;
                        }

                        final DriveContents driveContents = result
                                .getDriveContents();
                        Log.i(TAG, "New contents created.");
                        OutputStream outputStream = result.getDriveContents()
                                .getOutputStream();
                        try {
                            @SuppressWarnings("resource")
                            FileInputStream fileInputStream = new FileInputStream(
                                    file);
                            byte[] buffer = new byte[1024];
                            int bytesRead;
                            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                        } catch (IOException e1) {
                            Log.i(TAG, "Unable to write file contents.");
                        }
                        DriveFolder folder = mFolderDriveId.asDriveFolder();

                        MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                .setTitle(file.getName()).setStarred(true)
                                .build();

                        // create a file on root folder

                        folder.createFile(mGoogleApiClient, metadataChangeSet,
                                driveContents).setResultCallback(fileCallback);

                        // Drive.DriveApi
                        // .getRootFolder(mGoogleApiClient)
                        // .createFile(mGoogleApiClient,
                        // metadataChangeSet, driveContents)
                        // .setResultCallback(fileCallback);

                        try {
                        } catch (Exception e) {
                        }
                    }
                });
    }

    private void loadSdcardfiles(File aFile) {
        if (aFile.isFile()) {
            if (aFile.getAbsolutePath().endsWith(".mp3")) {
                listAllMusicFiles.add(aFile);
            }
        } else if (aFile.isDirectory()) {
            File[] listOfFiles = aFile.listFiles();
            if (listOfFiles != null) {
                for (int i = 0; i < listOfFiles.length; i++) {
                    if (listOfFiles[i].isFile()) {
                        loadSdcardfiles(listOfFiles[i]);
                    }

                }
            } else {
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API).addScope(Drive.SCOPE_FILE)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
        }
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
            mGoogleApiClient.connect();
        }
    }

    public void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
        if (!result.hasResolution()) {
            GoogleApiAvailability.getInstance()
                    .getErrorDialog(this, result.getErrorCode(), 0).show();
            return;
        }
        try {
            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (SendIntentException e) {
            Log.e(TAG, "Exception while starting resolution activity", e);
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
                1000).show();
        if (listAllMusicFiles.size() == 0) {
            return;
        } else {
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle("Siddharth").build();

            Drive.DriveApi.getRootFolder(mGoogleApiClient)
                    .createFolder(mGoogleApiClient, changeSet)
                    .setResultCallback(callback);

        }

    }

    @Override
    public void onConnectionSuspended(int cause) {
        Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
                .show();
    }

    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();
            for (int i = 0; i < listAllMusicFiles.size(); i++) {
                saveFileToDrive(listAllMusicFiles.get(i));
            }

        }
    };
    final ResultCallback<DriveFolderResult> callback = new ResultCallback<DriveFolderResult>() {
        @Override
        public void onResult(final DriveFolderResult result) {
            if (!result.getStatus().isSuccess()) {
                showMessage("Error while trying to create the folder");
                return;
            }
            showMessage("Created a folder: "
                    + result.getDriveFolder().getDriveId());
            mFolderDriveId = result.getDriveFolder().getDriveId();
            DriveFolder folder = Drive.DriveApi.getFolder(mGoogleApiClient,
                    result.getDriveFolder().getDriveId());
            folder.addChangeSubscription(mGoogleApiClient);

        }
    };

    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 with content: "
                    + result.getDriveFile().getDriveId());

        }
    };

    public class MyDriveEventService extends DriveEventService {

        @Override
        public void onChange(ChangeEvent event) {
            Log.d(TAG, event.toString());
            Drive.DriveApi.fetchDriveId(mGoogleApiClient,
                    mFolderDriveId.getResourceId()).setResultCallback(
                    idCallback);
        }

    }
}

任何人都可以建议我如何做到这一点,在此先感谢

1 个答案:

答案 0 :(得分:0)

最后是的,它在我提供的链接中...

这是我所做的改变

@Override
public void onConnected(Bundle connectionHint) {
    Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
            1000).show();
    if (listAllMusicFiles.size() == 0) {
        return;
    } else {
        if (count == 0) {
            count++;
            mcreateFolder();
        }
    }

}

public void mcreateFolder() {

    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(
            "Siddharth").build();
    Drive.DriveApi.getRootFolder(mGoogleApiClient)
            .createFolder(mGoogleApiClient, changeSet)
            .setResultCallback(callback);

}

final ResultCallback<DriveFolderResult> callback = new ResultCallback<DriveFolderResult>() {
    @Override
    public void onResult(final DriveFolderResult result) {
        if (!result.getStatus().isSuccess()) {
            showMessage("Error while trying to create the folder");
            return;
        }
        showMessage("Created a folder: "
                + result.getDriveFolder().getDriveId());
        mFolderDriveId = result.getDriveFolder().getDriveId();

        Drive.DriveApi.getFolder(mGoogleApiClient, mFolderDriveId)
                .addChangeListener(mGoogleApiClient, mChgeLstnr);

        mCnt = 0;
        mPoker = new Handler();
        mPoker.postDelayed(mPoke, mWait);

    }
};

final private ChangeListener mChgeLstnr = new ChangeListener() {
    @Override
    public void onChange(ChangeEvent event) {
        // showMessage("event: " + event + " resId: "
        // + event.getDriveId().getResourceId());

    }
};

private final Runnable mPoke = new Runnable() {
    public void run() {
        if (mPoker != null && mFolderDriveId != null
                && mFolderDriveId.getResourceId() == null
                && (mCnt++ < ENOUGH)) {
            MetadataChangeSet meta = new MetadataChangeSet.Builder()
                    .build();
            Drive.DriveApi
                    .getFolder(mGoogleApiClient, mFolderDriveId)
                    .updateMetadata(mGoogleApiClient, meta)
                    .setResultCallback(
                            new ResultCallback<DriveResource.MetadataResult>() {
                                @Override
                                public void onResult(
                                        DriveResource.MetadataResult result) {
                                    if (result.getStatus().isSuccess()
                                            && result.getMetadata()
                                                    .getDriveId()
                                                    .getResourceId() != null) {
                                        showMessage("resId COOL "
                                                + result.getMetadata()
                                                        .getDriveId()
                                                        .getResourceId());
                                        mPoker.removeCallbacksAndMessages(mPoke);
                                        Drive.DriveApi.fetchDriveId(
                                                mGoogleApiClient,
                                                result.getMetadata()
                                                        .getDriveId()
                                                        .getResourceId())
                                                .setResultCallback(
                                                        idCallback);
                                    } else {
                                        mPoker.postDelayed(mPoke,
                                                mWait *= 2);
                                    }
                                }
                            });
        } else {
            mPoker = null;
        }
    }
};

非常感谢@seanpj的精彩阐述。

cannot get folderId that i just created on google drive

Unpredictable result of DriveId.getResourceId() in Google Drive Android API

我非常感谢你的努力。