GoogleApiClient дает нулевой указатель, даже когда ему передается контекст при использовании API-интерфейса Fused Location в Android

Я пытаюсь реализовать Fused Location API в сервисе. Я сделал следующее кодирование, но я получаю сообщение об ошибке следующим образом:

  java.lang.RuntimeException: Unable to instantiate service com.locate.LocationDetails: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference

в следующей строке кода:

mGoogleApiClient = new GoogleApiClient.Builder(LocationDetails.this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(LocationDetails.this)
        .addApi(LocationServices.API)
        .build();

Мой код выглядит следующим образом:

public class LocationDetails extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    Broadcaster broadcaster;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    @Override
    public void onCreate() {
        super.onCreate();



    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    public LocationDetails() {
        // super();
      mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();


        mGoogleApiClient.connect();
      /*  mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000);*/
        Log.i("Service", "Started");


    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onConnected(Bundle bundle) {

        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (location == null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
        } else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("Connection", "Suspended");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        if (connectionResult.hasResolution()) {
            try {

                connectionResult.startResolutionForResult((Activity) getBaseContext(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i("connection err", "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    private void handleNewLocation(Location location) {
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();
        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        Log.i("location", "" + latLng);


    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i("On Changd Location", "" + location.getLatitude());

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.i("Provider", provider);

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

Я передаю context но все же NullPointer Exception,

Может кто-нибудь сказать мне, как исправить этот сбой и исправить код MT и во-вторых, у меня есть сомнения, что ли fused location api можно использовать с сервисом или нет?

1 ответ

Решение

Причина, по которой вы получаете NullPointerException потому что ты звонишь getBaseContext() в конструкторе.

Это приравнивается к this.getBaseContext(), а также this не может быть использован в качестве контекста в то время.

Больше информации здесь.

Просто переместите код из конструктора в onCreate():

@Override
public void onCreate() {
    super.onCreate();

    mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();


    mGoogleApiClient.connect();

    Log.i("Service", "Started");

}
Другие вопросы по тегам