android - 在android中的google drive api中选择帐户后, Intent 数据在 Activity 结果上为空

标签 android google-drive-api google-drive-android-api

下面是我的代码:

基础演示 Activity :

public abstract class BaseDemoActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "BaseDriveActivity";

    /**
     * DriveId of an existing folder to be used as a parent folder in
     * folder operations samples.
     */
    public static String EXISTING_FOLDER_ID = "CAESHDBCMlBoNlZTdkpaR2FTRTFaWW5wclNXRlFabXMYOiCWqeuO-FI=";

    /**
     * DriveId of an existing file to be used in file operation samples..
     */
    public static final String EXISTING_FILE_ID = "CAESHDBCMlBoNlZTdkpaR2FTRTFaWW5wclNXRlFabXMYOiCWqeuO-FI=";

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

    /**
     * Request code for auto Google Play Services error resolution.
     */
    protected static final int REQUEST_CODE_RESOLUTION = 1;

    /**
     * Next available request code.
     */
    protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;

    /**
     * Google API client.
     */
    public GoogleApiClient mGoogleApiClient;

    /**
     * Called when activity gets visible. A connection to Drive services need to
     * be initiated as soon as the activity is visible. Registers
     * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
     * activities itself.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();
    }

    /**
     * Handles resolution callbacks.
     */
    @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();
        }
    }

    /**
     * Called when activity gets invisible. Connection to Drive service needs to
     * be disconnected as soon as an activity is invisible.
     */
    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    /**
     * Called when {@code mGoogleApiClient} is connected.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "GoogleApiClient connected");
    }

    /**
     * Called when {@code mGoogleApiClient} is disconnected.
     */
    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "GoogleApiClient connection suspended");
    }

    /**
     * Called when {@code mGoogleApiClient} is trying to connect but failed.
     * Handle {@code result.getResolution()} if there is a resolution is
     * available.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
        if (!result.hasResolution()) {
            // show the localized error dialog.
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
            return;
        }
        try {
            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (SendIntentException e) {
            Log.e(TAG, "Exception while starting resolution activity", e);
        }
    }

    /**
     * Shows a toast message.
     */
    public void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    /**
     * Getter for the {@code GoogleApiClient}.
     */
    public GoogleApiClient getGoogleApiClient() {
      return mGoogleApiClient;
    }


}

选择文件夹 Activity :

public class PickFolderWithOpenerActivity extends BaseDemoActivity {

    private static final String TAG = "PickFolderWithOpenerActivity";

    private static final int REQUEST_CODE_OPENER = 1;

    @Override
    public void onConnected(Bundle connectionHint) {
        super.onConnected(connectionHint);

        IntentSender intentSender = Drive.DriveApi
                .newOpenFileActivityBuilder()
                .setMimeType(new String[] { DriveFolder.MIME_TYPE })
                .build(getGoogleApiClient());
        try {
            startIntentSenderForResult(
                    intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
        } catch (SendIntentException e) {
          Log.w(TAG, "Unable to send intent", e);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
        case REQUEST_CODE_OPENER:
            if (resultCode == RESULT_OK) {
                DriveId driveId = (DriveId) data.getParcelableExtra(
                        OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
                showMessage("Selected folder's ID: " + driveId.getResourceId().toString());
                BaseDemoActivity.EXISTING_FOLDER_ID = driveId.getResourceId().toString();
            }
            finish();
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
        }
    }

}

日志:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.drive.testdemo/com.drive.testdemo.PickFolderWithOpenerActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3432)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3475)
    at android.app.ActivityThread.access$1300(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5086)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
    at com.drive.testdemo.PickFolderWithOpenerActivity.onActivityResult(PickFolderWithOpenerActivity.java:67)
    at android.app.Activity.dispatchActivityResult(Activity.java:5446)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3428)

最佳答案

我遇到了同样的连接问题,后来我找到了以下解决方案,

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_CODE_OPENER:
        if (resultCode == RESULT_OK) {

            final DriveId folderId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
            showMessage("Selected folder's ID: " + folderId);

            AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){

                int intReturnType = 0;
                @Override
                protected void onPostExecute(Void result) {
                    //super.onPostExecute(result);
                    //Do Logic...
                }

                @Override
                protected Void doInBackground(Void... params) {

                    ConnectionResult resultApi = getGoogleApiClient().blockingConnect();
                    if (!resultApi.isSuccess()) {
                        return null;
                    }

                    @SuppressWarnings("deprecation")
                    DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), folderId);
                    DriveResource.MetadataResult result = folder.getMetadata(getGoogleApiClient()).await();
                    if (!result.getStatus().isSuccess()) {
                        Log.d("Folder", "Problem while trying to fetch metadata.");
                        return null;
                    }

                    Metadata metadata = result.getMetadata();
                    if (metadata.isTrashed()) {
                        Log.d("Folder", "Folder is trashed");
                        return null;
                    }

                    Log.d("FolderName", metadata.getTitle());
                    return null;
                }
            };
            task.execute();
        }
        break;
    default:
        super.onActivityResult(requestCode, resultCode, data);
        break;
    }
}

关于android - 在android中的google drive api中选择帐户后, Intent 数据在 Activity 结果上为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700271/

相关文章:

Android SurfaceView 为空

android - 如何从 Android 应用程序共享 Google Drive 文件?

Java::如何将 Google Drive 中存储的 Excel 文件导入到特定的 Google 电子表格

javascript - 通过谷歌应用脚​​本将文件上传到谷歌驱动器时出现问题

android - 适用于 Android 的 Google 日历 API - 如何将房间添加为 Activity 的 guest ?

三星 Galaxy S3、S4、S5 的 Android 相机/图片方向问题

python - pydrive 仅从列表中获取文件夹

android - 如何在 Android Studio 中以编程方式上传和下载 Google Drive 上的任何文件

google-drive-api - 新的 Google Drive Android API (GDAA) 中报告的已删除文件状态不可靠

java - 安卓/Java : Is there a way to call the return of the method after a listener triggered?