LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)为空

时间:2016-06-19 20:47:20

标签: java android maps

运行包含此onMapReady实施的活动时出现以下错误:

  

java.lang.NullPointerException:尝试调用虚方法   '对象的'double android.location.Location.getLatitude()'   参考

问题是mLastLocation似乎是空的。

@Override
public void onMapReady(GoogleMap map) {

    distanceTraveled = 0;

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setBearingRequired(true);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        float LOCATION_REFRESH_DISTANCE = 5000;
        long LOCATION_REFRESH_TIME = 0;
        mlocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                updateLocation(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, mlocationListener);
    }

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NO Sleep");
    wakeLock.acquire();

    LatLng myPosition = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
    map.addMarker(new MarkerOptions().position(myPosition).title("myPosition"));
    map.moveCamera(CameraUpdateFactory.newLatLng(myPosition));

    draw();
    tracking = true;
    startTime = System.currentTimeMillis();

}

这就是我获取mLastLocation的方法

@Override
public void onConnected(Bundle connectionHint) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }
}

有没有人知道为什么LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)在我的代码中变为空?

编辑:全班代码

package com.noureddine_ouertani.www.wocelli50;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;


public class NeueRouteAufzeichnen extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private LocationManager locationManager;
private Location mLastLocation;
private Location previousLocation;
private long distanceTraveled;

private boolean tracking = false;
private long startTime;
private PowerManager.WakeLock wakeLock;
private boolean gpsFix;

private static final double MILLISECONDS_PER_HOUR = 100 * 60 * 60;
private static final double MILES_PER_KILOMETER = 0.621371192;
private static final int MAP_ZOOM = 18;

private List<Location> locations;

private GoogleApiClient mGoogleApiClient;
LocationListener mlocationListener;
GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    setContentView(R.layout.activity_neue_route_aufzeichnen);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    locations = new ArrayList<Location>();
}

protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnected(Bundle connectionHint) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }
}

@Override
public void onConnectionSuspended(int i) {

}

public void addPoint(Location location) {
    locations.add(location);
}

@Override
public void onMapReady(GoogleMap map) {

    distanceTraveled = 0;

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setBearingRequired(true);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        float LOCATION_REFRESH_DISTANCE = 5000;
        long LOCATION_REFRESH_TIME = 0;
        mlocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                updateLocation(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, mlocationListener);
    }

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NO Sleep");
    wakeLock.acquire();

    LatLng myPosition = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
    map.addMarker(new MarkerOptions().position(myPosition).title("myPosition"));
    map.moveCamera(CameraUpdateFactory.newLatLng(myPosition));

    draw();
    tracking = true;
    startTime = System.currentTimeMillis();

}

protected void updateLocation(Location location) {

    if (location != null && gpsFix == true) {
        addPoint(location);

        if (previousLocation != null)
            distanceTraveled += location.distanceTo(previousLocation);
    }
    previousLocation = location;
}

public void draw() {

    if (map == null) {
        return;
    }

    PolylineOptions options = new PolylineOptions();

    options.color(Color.parseColor("#CC0000FF"));
    options.width(5);
    options.visible(true);

    for (Location locRecorded : locations) {
        options.add(new LatLng(locRecorded.getLatitude(),
                locRecorded.getLongitude()));
    }

    map.addPolyline(options);

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

0 个答案:

没有答案