Android Google Drive implementation : getting the exception “java.lang.ClassNotFoundException: com.google.android.gms.common.api.Scope”

只愿长相守 提交于 2020-01-07 03:21:48

问题


My implementation apparently has no errors and when i try to load this example i get the exception

Class not found when unmarshalling: com.google.android.gms.common.api.Scope java.lang.ClassNotFoundException: com.google.android.gms.common.api.Scope at java.lang.Class.classForName(Native Method) at java.lang.Class.forName(Class.java:308) at java.lang.Class.forName(Class.java:272) at android.os.Parcel.readParcelableCreator(Parcel.java:2275) at android.os.Parcel.readParcelable(Parcel.java:2239) at android.os.Parcel.readParcelableArray(Parcel.java:2332) at android.os.Parcel.readValue(Parcel.java:2200) at android.os.Parcel.readArrayMapInternal(Parcel.java:2479) at android.os.BaseBundle.unparcel(BaseBundle.java:221) at android.os.BaseBundle.getString(BaseBundle.java:918) at android.content.Intent.getStringExtra(Intent.java:5386) at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:1799) at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:1353) at com.android.server.am.ActivityManagerService.startActivityInPackage(ActivityManagerService.java:5214) at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:257) at com.android.server.am.ActivityManagerService.startActivityIntentSender(ActivityManagerService.java:5012) at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:260) at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3128) at android.os.Binder.execTransact(Binder.java:461) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.api.Scope" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

This is my code:

public class MainActivity extends AppCompatActivity  implements ConnectionCallbacks,
        OnConnectionFailedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

        private static final String TAG = "MainActivity";
        private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
        private static final int REQUEST_CODE_CREATOR = 2;
        private static final int REQUEST_CODE_RESOLUTION = 3;
        private GoogleApiClient mGoogleApiClient;
        private Bitmap mBitmapToSave;

       private void saveFileToDrive() {
        Log.i(TAG, "saveFileToDrive() Creating new content.");
        final Bitmap image = mBitmapToSave;
        Drive.DriveApi.newDriveContents(mGoogleApiClient)
                .setResultCallback(new ResultCallback<DriveContentsResult>() {
                    @Override
                    public void onResult(DriveContentsResult result) {
                        if (!result.getStatus().isSuccess()) {
                            Log.i(TAG, "Failed to create new content.");
                            return;
                        }
                        Log.i(TAG, "New content has been created.");
                        OutputStream outputStream = result.getDriveContents().getOutputStream();
                         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("Android Photo.png").build();
                        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.");
                        }
                    }
                });
    }

    @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(final int requestCode, final int resultCode, final Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_CAPTURE_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    mBitmapToSave = (Bitmap) data.getExtras().get("data");
                }
                break;
            case REQUEST_CODE_CREATOR:
                if (resultCode == RESULT_OK) {
                    Log.i(TAG, "Image successfully saved.");
                    mBitmapToSave = null;
                    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                            REQUEST_CODE_CAPTURE_IMAGE);
                }
                break;
        }
    }

    @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) {
        Log.i(TAG, "API client connected.");
        if (mBitmapToSave == null) {
            startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                    REQUEST_CODE_CAPTURE_IMAGE);
            return;
        }
        saveFileToDrive();
    }

    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "GoogleApiClient connection suspended");
    }
}

And my build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.jorgesys.googledrive"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-drive:8.4.0'
}

回答1:


Well i have found that the real problem was caused when i have added this dependency to my build.gradle file :

 compile 'com.google.android.gms:play-services-drive:8.4.0'

so i tried to enable multidex thinking that probably my problem was the 64k limit of references, then i have added the multidex support, and now is working with no problem.

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        ...
        ...
        multiDexEnabled true
    }
...
...


来源:https://stackoverflow.com/questions/43500747/android-google-drive-implementation-getting-the-exception-java-lang-classnotf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!