web-dev-qa-db-fra.com

NullPointerException lors de la tentative de vérification des autorisations

J'essaie de vérifier si l'utilisateur a bien Android.Manifest.permission.ACCESS_FINE_LOCATION. Lors de l'exécution de l'application, j'obtiens une erreur NullPointerException.

package dtt.romano.rsrpechhulp;

import Android.app.Activity;
import Android.content.Context;
import Android.content.IntentSender;
import Android.content.pm.PackageManager;
import Android.location.Location;
import Android.os.Bundle;
import Android.support.annotation.NonNull;
import Android.support.v4.app.ActivityCompat;
import Android.util.Log;

import com.google.Android.gms.common.ConnectionResult;
import com.google.Android.gms.common.api.GoogleApiClient;
import com.google.Android.gms.location.LocationListener;
import com.google.Android.gms.location.LocationRequest;
import com.google.Android.gms.location.LocationServices;

public class LocationProvider extends MainActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,LocationListener {

public abstract interface LocationCallback {
    public void handleNewLocation(Location location);
}

public static final String TAG = LocationProvider.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public LocationProvider(Context context, LocationCallback callback) {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationCallback = callback;

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

    mContext = context;
}

public void connect() {
    mGoogleApiClient.connect();
}

public void disconnect() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

public void locationUpdate(){
    if (ActivityCompat.checkSelfPermission(this, Android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{
                Android.Manifest.permission.ACCESS_FINE_LOCATION
        }, 10);
    }else{
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            mLocationCallback.handleNewLocation(location);
        }
    }
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");
    locationUpdate();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 10:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationUpdate();
            }
            return;
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution() && mContext instanceof Activity) {
        try {
            Activity activity = (Activity)mContext;
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        /*
         * Thrown if Google Play services canceled the original
         * PendingIntent
         */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
        /*
         * If no resolution is available, display a dialog to the
         * user with the error.
         */
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

@Override
public void onLocationChanged(Location location) {
    mLocationCallback.handleNewLocation(location);
}
}

Voici le journal des erreurs:

Java.lang.NullPointerException: Attempt to invoke virtual method 'int Android.content.Context.checkPermission(Java.lang.String, int, int)' on a null object reference                                                          
 at Android.content.ContextWrapper.checkPermission(ContextWrapper.Java:637)
 at Android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.Java:387)
at dtt.romano.rsrpechhulp.LocationProvider.onConnected(LocationProvider.Java:68)
at com.google.Android.gms.common.internal.zzk.zzk(Unknown Source)
at com.google.Android.gms.common.api.internal.zzj.zzi(Unknown Source)
at com.google.Android.gms.common.api.internal.zzh.zzpx(Unknown Source)
at com.google.Android.gms.common.api.internal.zzh.onConnected(Unknown Source)
at com.google.Android.gms.common.api.internal.zzl.onConnected(Unknown Source)
at com.google.Android.gms.common.api.internal.zzc.onConnected(Unknown Source)
at com.google.Android.gms.common.internal.zzj$zzg.zzqL(Unknown Source)
at com.google.Android.gms.common.internal.zzj$zza.zzc(Unknown Source)
at com.google.Android.gms.common.internal.zzj$zza.zzw(Unknown Source)
at com.google.Android.gms.common.internal.zzj$zzc.zzqN(Unknown Source)
at com.google.Android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
at Android.os.Handler.dispatchMessage(Handler.Java:102)
at Android.os.Looper.loop(Looper.Java:148)
at Android.app.ActivityThread.main(ActivityThread.Java:5417)
at Java.lang.reflect.Method.invoke(Native Method)
at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:726)
at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:616)
17
B. Bob
if (ActivityCompat.checkSelfPermission((Activity)mContext, Android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions((Activity)mContext, new String[]{
            Android.Manifest.permission.ACCESS_FINE_LOCATION
    }, 10);
}

Essayez d'utiliser (activité) mContext au lieu de cela. cela peut aider.

40
Nitin Jain
if (ActivityCompat.checkSelfPermission(ActivityName.this, Android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityName.this, new String[]{
        Android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);

}

Essayez avec votre nom d’activité.

0
Joel George