简体   繁体   English

如何解决与 api 集成到 android 应用程序相关的错误?

[英]How to resolve the error related to google drive api integration to android app?

This app is to upload files from android app to google drive.这个应用程序是从 android 应用程序上传文件到谷歌驱动器。 So here i had used google drive api, for enabling google drive api i had created a project and credentials in Google API Console.所以在这里我使用了谷歌驱动器 api,为了启用谷歌驱动器 api 我在谷歌 API 控制台中创建了一个项目和凭据。 When running my app i am getting the error given below.运行我的应用程序时出现以下错误。 How resolve this error??这个错误怎么解决??

Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.app.appfordrive.DriveServiceHelper.createFile(java.lang.String)' on a null object reference at com.app.appfordrive.MainActivity.uploadPdfFile(MainActivity.java:110) at java.lang.reflect.Method.invoke(Native Method)尝试调用虚拟方法 'com.google.android.gms.tasks.Task com.app.appfordrive.DriveServiceHelper.createFile(java.lang.String)' 在 null object 引用 8816897MactivityPActivityAppdapp.load.load. MainActivity.java:110)位于 java.lang.reflect.Method.invoke(本机方法)

2021-10-06 17:01:11.259 1763-2037/com.google.android.gms E/GmsClient: unable to connect to service: com.google.android.gms.auth.key.retrieval.service.START on com.google.android.gms 2021-10-06 17:01:11.259 1763-2037/com.google.android.gms E/GmsClient:无法连接到服务:com.google.android.gms.auth.key.retrieval.706.START09 on 880166 .google.android.gms

MainActivity.java MainActivity.java

    private static final String TAG = "MainActivity";
    private DriveServiceHelper mDriveServiceHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestSignIn();
    }
    private void requestSignIn() {
        Log.v(TAG,"Requesting sign-in");

        GoogleSignInOptions signInOptions =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
                        .build();
        GoogleSignInClient client = GoogleSignIn.getClient(this, signInOptions);

        // The result of the sign-in Intent is handled in onActivityResult.
        startActivityForResult(client.getSignInIntent(), 400);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 400:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    handleSignInResult(data);
                }
                break;

        }
    }

    private void handleSignInResult(Intent data) {
        GoogleSignIn.getSignedInAccountFromIntent(data)
                .addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
                    @Override
                    public void onSuccess(GoogleSignInAccount googleSignInAccount) {
                        // Use the authenticated account to sign in to the Drive service.
                        GoogleAccountCredential credential =
                                GoogleAccountCredential.usingOAuth2(MainActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
                        credential.setSelectedAccount(googleSignInAccount.getAccount());



                        Drive googleDriveService =
                                new Drive.Builder(
                                        AndroidHttp.newCompatibleTransport(),
                                        new GsonFactory(),
                                        credential)
                                        .setApplicationName("Drive API Migration")
                                        .build();
                        mDriveServiceHelper = new DriveServiceHelper(googleDriveService);
                    }

                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure (@Nullable Exception e){


                    }
                });
    }



    public void uploadPdfFile(View view){
        ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("Uploading to Google Drive");
        progressDialog.setMessage("Please wait");
        progressDialog.show();
        String filePath ="C://Users/CABAL/Downloads/certificate.pdf";
        mDriveServiceHelper.createFile(filePath).addOnSuccessListener(new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String s) {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(),"Uploaded Successfully",Toast.LENGTH_LONG).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(),"Check your google drive api",Toast.LENGTH_LONG).show();

            }
        });


    }
}

DriveServiceHelper.java DriveServiceHelper.java

    public class DriveServiceHelper {
     private final Executor mExecutor = Executors.newSingleThreadExecutor();
     private final Drive mDriveService;
     public DriveServiceHelper(Drive mDriveService)
     {
        this.mDriveService = mDriveService;
     }
     public Task<String> createFile(String filePath) {
        return Tasks.call(mExecutor, () -> {
            File fileMetadata = new File();
            fileMetadata.setName("my file");
            java.io.File file = new java.io.File(filePath);
            FileContent metaContent = new FileContent("application/pdf",file);
            File myFile = null;
            try{
                myFile = mDriveService.files().create(fileMetadata,metaContent).execute();
            }catch (Exception e){
                e.printStackTrace();
            }
            if (myFile == null) {
                throw new IOException("Null result when requesting file creation.");
            }

            return myFile.getId();
        });



     }

}

build.gradle build.gradle

    plugins {
      id 'com.android.application'
    }

    android {
      compileSdkVersion 31
      buildToolsVersion "30.0.3"

     defaultConfig {
        applicationId "com.app.appfordrive"
        minSdkVersion 16
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE.txt'
            exclude 'META-INF/license.txt'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/NOTICE.txt'
            exclude 'META-INF/notice.txt'
            exclude 'META-INF/ASL2.0'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    // g drive libs
    implementation 'com.google.android.gms:play-services-auth:19.2.0'
    implementation 'com.google.http-client:google-http-client-gson:1.26.0'
    implementation('com.google.api-client:google-api-client-android:1.26.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0') {
        exclude group: 'org.apache.httpcomponents'
    }
}

AndroidManifest.xml AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.appfordrive">
    <!-- Permissions required by GoogleAuthUtil -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And Is it possible to use google drive api without using google sign in/by using default path to drive?并且是否可以在不使用谷歌登录/使用默认路径驱动的情况下使用谷歌驱动器 api?

The cause of the NullPointerException is that you are executing mDriveServiceHelper.createFile(filePath) when mDriveServiceHelper is still null . NullPointerException的原因是当mDriveServiceHelper仍然是null时,您正在执行mDriveServiceHelper.createFile(filePath)

Presumably that means that your OnSuccessListener<GoogleSignInAccount> has not been called, because that is where you initialize mDriveServiceHelper .大概这意味着您的OnSuccessListener<GoogleSignInAccount>尚未被调用,因为这是您初始化mDriveServiceHelper的地方。


And Is it possible to use the Google Drive API without using Google sign in by using default path to drive?是否可以通过使用默认驱动器路径在不使用 Google 登录的情况下使用 Google Drive API?

I think that the answer is No.我认为答案是否定的。

I assume that you are talking about something that will "mount" Google Drive via a FUSE file system, or do the equivalent of Ubuntu's gio mount .我假设您正在谈论的是通过 FUSE 文件系统“挂载”Google Drive 的东西,或者相当于 Ubuntu 的gio mount I don't think that either of those is available on Android platforms.我认为这两个在 Android 平台上都不可用。 And even if they were available, it would be necessary to supply the Google sign-in credentials each time the drive was mounted.即使它们可用,也有必要在每次安装驱动器时提供 Google 登录凭据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决下面给出的与使用 Spring Boot 和邮递员在谷歌驱动器中上传文件相关的错误? - How to resolve the error given below related to the file upload in google drive using Spring boot and postman? 如何使用Google Drive Android API删除Google Drive上的文件 - How to delete a file on google drive using Google Drive Android API 如何在Android上设置Google Drive API? - How to set up Google Drive API on android? 如何解决不足的文件权限创建Google服务帐户团队驱动器的错误? - How to resolve Google Service Account Team Drive creation error of insufficientFilePermissions? 谷歌驱动器配额使用android api驱动器 - google drive quota using android api for drive Google Drive Android API如何将音频文件上传到我的驱动器? 如何同步驱动器文件? - Google Drive Android API how to upload a audio file to my drive ? How to sync drive files? 我的Android应用中的Google云端硬盘返回错误400 - Google Drive Returning Error 400 in my Android app 如何解决与httpClientConfigCallback相关的错误? - How to resolve error related to httpClientConfigCallback? 如何使用NetBeans开发适用于Google Drive API的桌面应用 - How to use NetBeans to develop desktop app for Google Drive API Google Drive API通过Google App Engine - Google Drive API through Google App Engine
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM