gmail api出错

时间:2016-12-14 19:38:34

标签: android email nullpointerexception gmail-api

下午好,我正在使用Gmail APi,但是当我去执行标签列表时,它显示我错了...

我的代码是:

    package com.medical.germany.reportesgermany.Vista;

import android.Manifest;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;

import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
import com.medical.germany.reportesgermany.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class Splash extends AppCompatActivity implements View.OnClickListener,
        EasyPermissions.PermissionCallbacks {

    ///Variables locales
    Button boton_inicio;
    ProgressDialog mProgress;
    Toast mensaje;

    Intent intent;

    GoogleAccountCredential mCredential;


    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_AUTHORIZATION = 1001;
    static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
    static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;

    private static final String PREF_ACCOUNT_NAME = "accountName";
    private static final String[] SCOPES = { GmailScopes.GMAIL_LABELS,GmailScopes.MAIL_GOOGLE_COM,GmailScopes.GMAIL_MODIFY,GmailScopes.GMAIL_READONLY,GmailScopes.GMAIL_METADATA };

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

        //Inicializar variables
        boton_inicio= (Button) findViewById(R.id.button_iniciar);

        mProgress = new ProgressDialog(this);
        mProgress.setMessage("Conectandose a Gmail...");

        // Initialize credentials and service object.
        mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());

        //Implementar eventos
        boton_inicio.setOnClickListener(this);

    }

    /**
     * Attempt to call the API, after verifying that all the preconditions are
     * satisfied. The preconditions are: Google Play Services installed, an
     * account was selected and the device currently has online access. If any
     * of the preconditions are not satisfied, the app will prompt the user as
     * appropriate.
     */
    private void getResultsFromApi() {
        if (! isGooglePlayServicesAvailable()) {
            acquireGooglePlayServices();
        } else if (mCredential.getSelectedAccountName() == null) {
            chooseAccount();
        } else if (! isDeviceOnline()) {
            mensaje=Toast.makeText(this,"Conexión no disponible",Toast.LENGTH_SHORT);
            mensaje.show();
        } else {
            new MakeRequestTask(mCredential).execute();
        }
    }

    /**
     * Attempts to set the account used with the API credentials. If an account
     * name was previously saved it will use that one; otherwise an account
     * picker dialog will be shown to the user. Note that the setting the
     * account to use with the credentials object requires the app to have the
     * GET_ACCOUNTS permission, which is requested here if it is not already
     * present. The AfterPermissionGranted annotation indicates that this
     * function will be rerun automatically whenever the GET_ACCOUNTS permission
     * is granted.
     */
    @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
    private void chooseAccount() {
        if (EasyPermissions.hasPermissions(
                this, Manifest.permission.GET_ACCOUNTS)) {
            String accountName = getPreferences(Context.MODE_PRIVATE)
                    .getString(PREF_ACCOUNT_NAME, null);
            if (accountName != null) {
                mCredential.setSelectedAccountName(accountName);
                getResultsFromApi();
            } else {
                // Start a dialog from which the user can choose an account
                startActivityForResult(
                        mCredential.newChooseAccountIntent(),
                        REQUEST_ACCOUNT_PICKER);
            }
        } else {
            // Request the GET_ACCOUNTS permission via a user dialog
            EasyPermissions.requestPermissions(
                    this,
                    "Esta app necesita acceder a tu cuenta de google",
                    REQUEST_PERMISSION_GET_ACCOUNTS,
                    Manifest.permission.GET_ACCOUNTS);
        }
    }

    /**
     * Called when an activity launched here (specifically, AccountPicker
     * and authorization) exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     * @param requestCode code indicating which activity result is incoming.
     * @param resultCode code indicating the result of the incoming
     *     activity result.
     * @param data Intent (containing result data) returned by incoming
     *     activity result.
     */
    @Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode != RESULT_OK) {
                    mensaje=Toast.makeText(this,
                            "Esta aplicación requiere Servicios de google, por favor instalar ",Toast.LENGTH_LONG);
                    mensaje.show();
                } else {
                    getResultsFromApi();
                }
                break;
            case REQUEST_ACCOUNT_PICKER:
                if (resultCode == RESULT_OK && data != null &&
                        data.getExtras() != null) {
                    String accountName =
                            data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        SharedPreferences settings =
                                getPreferences(Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(PREF_ACCOUNT_NAME, accountName);
                        editor.apply();
                        mCredential.setSelectedAccountName(accountName);
                        getResultsFromApi();
                    }
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode == RESULT_OK) {
                    getResultsFromApi();
                }
                break;
        }
    }

    /**
     * Respond to requests for permissions at runtime for API 23 and above.
     * @param requestCode The request code passed in
     *     requestPermissions(android.app.Activity, String, int, String[])
     * @param permissions The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions
     *     which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(
                requestCode, permissions, grantResults, this);
    }

    /**
     * Callback for when a permission is granted using the EasyPermissions
     * library.
     * @param requestCode The request code associated with the requested
     *         permission
     * @param list The requested permission list. Never null.
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Do nothing.
    }

    /**
     * Callback for when a permission is denied using the EasyPermissions
     * library.
     * @param requestCode The request code associated with the requested
     *         permission
     * @param list The requested permission list. Never null.
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Do nothing.
    }

    /**
     * Checks whether the device currently has a network connection.
     * @return true if the device has a network connection, false otherwise.
     */
    private boolean isDeviceOnline() {
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    /**
     * Check that Google Play services APK is installed and up to date.
     * @return true if Google Play Services is available and up to
     *     date on this device; false otherwise.
     */
    private boolean isGooglePlayServicesAvailable() {
        GoogleApiAvailability apiAvailability =
                GoogleApiAvailability.getInstance();
        final int connectionStatusCode =
                apiAvailability.isGooglePlayServicesAvailable(this);
        return connectionStatusCode == ConnectionResult.SUCCESS;
    }

    /**
     * Attempt to resolve a missing, out-of-date, invalid or disabled Google
     * Play Services installation via a user dialog, if possible.
     */
    private void acquireGooglePlayServices() {
        GoogleApiAvailability apiAvailability =
                GoogleApiAvailability.getInstance();
        final int connectionStatusCode =
                apiAvailability.isGooglePlayServicesAvailable(this);
        if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
            showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
        }
    }


    /**
     * Display an error dialog showing that Google Play Services is missing
     * or out of date.
     * @param connectionStatusCode code describing the presence (or lack of)
     *     Google Play Services on this device.
     */
    void showGooglePlayServicesAvailabilityErrorDialog(
            final int connectionStatusCode) {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        Dialog dialog = apiAvailability.getErrorDialog(
               this,
                connectionStatusCode,
                REQUEST_GOOGLE_PLAY_SERVICES);
        dialog.show();
    }

    @Override
    public void onClick(View v) {

        getResultsFromApi();
        //intent = new Intent(this, Pantalla_inicio.class);
        //startActivity(intent);
    }



    /**
     * An asynchronous task that handles the Gmail API call.
     * Placing the API calls in their own task ensures the UI stays responsive.
     */
    private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
        private com.google.api.services.gmail.Gmail mService = null;
        private Exception mLastError = null;

        MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.gmail.Gmail.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("Reportes Germany")
                    .build();
        }

        /**
         * Background task to call Gmail API.
         *
         * @param params no parameters needed for this task.
         */
        @Override
        protected List<String> doInBackground(Void... params) {
            try {
                return getDataFromApi();
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        /**
         * Fetch a list of Gmail labels attached to the specified account.
         *
         * @return List of Strings labels.
         * @throws IOException
         */
        private List<String> getDataFromApi() throws IOException {
            // Get the labels in the user's account.
            String user = "me";
            List<String> labels = new ArrayList<>();
            ListLabelsResponse listResponse =
                    mService.users().labels().list(user).execute();
            for (Label label : listResponse.getLabels()) {
                labels.add(label.getName());
            }
            return labels;
        }


        @Override
        protected void onPreExecute() {
            mProgress.show();
        }

        @Override
        protected void onPostExecute(List<String> output) {
            mProgress.hide();
            if (output == null || output.size() == 0) {
                mensaje= Toast.makeText(getApplicationContext(),"Sin resultados",Toast.LENGTH_LONG);
                mensaje.show();
            } else {
                output.add(0, "Recibiendo datos: ");
                mensaje= Toast.makeText(getApplicationContext(), TextUtils.join("\n", output),Toast.LENGTH_LONG);
                mensaje.show();
            }
        }

        @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            REQUEST_AUTHORIZATION);
                } else {
                    mensaje= Toast.makeText(getApplicationContext(),"El siguiente error ocurrió::\n"
                            + mLastError.getMessage(),Toast.LENGTH_SHORT);
                    mensaje.show();
                }
            } else {
                mensaje= Toast.makeText(getApplicationContext(), "Petición cancelada.",Toast.LENGTH_SHORT);
                mensaje.show();
            }
        }



    }

}

这与“Google Developers”的代码相同,错误是:

12/14 15:33:36: Launching app
$ adb push C:\Users\Miguel\Programacion\Android\AndroidStudioProjects\ReportesGermany\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.medical.germany.reportesgermany
$ adb shell pm install -r "/data/local/tmp/com.medical.germany.reportesgermany"
open: Permission denied
BT INFO: 2.2
BT INFO: 2.2
    pkg: /data/local/tmp/com.medical.germany.reportesgermany
Success


$ adb shell am start -n "com.medical.germany.reportesgermany/com.medical.germany.reportesgermany.Vista.Splash" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3198 on device huawei-g526_l22-88e3ab3c7e0c
E/Trace: error opening trace file: No such file or directory (2)
D/ActivityThread: setTargetHeapUtilization:0.75
D/ActivityThread: setTargetHeapIdealFree:8388608
D/ActivityThread: setTargetHeapConcurrentStart:2097152
W/dalvikvm: Refusing to reopen boot DEX '/system/framework/hwframework.jar'
W/dalvikvm: VFY: unable to resolve virtual method 269: Landroid/app/Application;.registerOnProvideAssistDataListener (Landroid/app/Application$OnProvideAssistDataListener;)V
W/dalvikvm: VFY: unable to resolve virtual method 272: Landroid/app/Application;.unregisterOnProvideAssistDataListener (Landroid/app/Application$OnProvideAssistDataListener;)V
I/InstantRun: Instant Run Runtime started. Android package is com.medical.germany.reportesgermany, real application class is null.
W/InstantRun: No instant run dex files added to classpath
I/ActivityThread: Pub com.medical.germany.reportesgermany: com.medical.germany.reportesgermany.Datos.Provider
E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources
W/dalvikvm: VFY: unable to resolve check-cast 2277 (Landroid/util/ArrayMap;) in Lcom/android/tools/fd/runtime/MonkeyPatcher;
E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.MonkeyPatcher.pruneResourceCache
W/dalvikvm: VFY: unable to resolve const-class 2277 (Landroid/util/ArrayMap;) in Lcom/android/tools/fd/runtime/MonkeyPatcher;
W/dalvikvm: VFY: unable to resolve interface method 20292: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
W/dalvikvm: VFY: unable to resolve interface method 20294: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
W/dalvikvm: VFY: unable to resolve interface method 20298: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
W/dalvikvm: VFY: unable to resolve virtual method 837: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
W/dalvikvm: VFY: unable to resolve virtual method 859: Landroid/content/res/TypedArray;.getType (I)I
W/dalvikvm: VFY: unable to resolve virtual method 800: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
W/dalvikvm: VFY: unable to resolve virtual method 802: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
W/dalvikvm: VFY: unable to resolve instanceof 177 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
W/dalvikvm: VFY: unable to resolve virtual method 550: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
I/Adreno200-EGL: <qeglDrvAPI_eglInitialize:269>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_2.3.04.01.01.32.125_msm8960_JB_2.2_RB2.3_CL3228873_release_AU (CL3228873)
                 Build Date: 03/01/13 Fri
                 Local Branch: 
                 Remote Branch: m/jb_2.2_rb2.3
                 Local Patches: NONE
                 Reconstruct Branch: AU_LINUX_ANDROID_JB_2.3.04.01.01.32.125 + 49716de + 6d091ee +  NOTHING
D/AudioManager: currentDeviceType = 1
E/dalvikvm: Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.zze.zzas
W/dalvikvm: VFY: unable to resolve check-cast 274 (Landroid/os/UserManager;) in Lcom/google/android/gms/common/zze;
W/dalvikvm: VFY: unable to resolve virtual method 757: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.internal.zzacw.zzg
W/dalvikvm: VFY: unable to resolve check-cast 31 (Landroid/app/AppOpsManager;) in Lcom/google/android/gms/internal/zzacw;
W/dalvikvm: VFY: unable to resolve virtual method 327: Landroid/app/Fragment;.requestPermissions ([Ljava/lang/String;I)V
W/dalvikvm: VFY: unable to resolve virtual method 302: Landroid/app/Fragment;.getChildFragmentManager ()Landroid/app/FragmentManager;
W/dalvikvm: VFY: unable to resolve virtual method 332: Landroid/app/Fragment;.shouldShowRequestPermissionRationale (Ljava/lang/String;)Z
W/EasyPermissions: hasPermissions: API version < M, returning true by default
W/AsyncTask: java.lang.InterruptedException
                 at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1280)
                 at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:219)
                 at java.util.concurrent.FutureTask.get(FutureTask.java:82)
                 at android.os.AsyncTask$3.done(AsyncTask.java:295)
                 at java.util.concurrent.FutureTask$Sync.innerCancel(FutureTask.java:293)
                 at java.util.concurrent.FutureTask.cancel(FutureTask.java:75)
                 at android.os.AsyncTask.cancel(AsyncTask.java:467)
                 at com.medical.germany.reportesgermany.Vista.Splash$MakeRequestTask.doInBackground(Splash.java:324)
                 at com.medical.germany.reportesgermany.Vista.Splash$MakeRequestTask.doInBackground(Splash.java:300)
                 at android.os.AsyncTask$2.call(AsyncTask.java:287)
                 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                 at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                 at java.lang.Thread.run(Thread.java:856)

异常的消息是:“El siguienteerrorauurrió:null”。如果您需要更多信息,请询问我。

编辑:错误发生在:

ListLabelsResponse listResponse =
                    mService.users().labels().list(user).execute();

但我不知道是什么......

0 个答案:

没有答案