我试图为一个位置获取2个变量,但它返回null。我不知道我做错了什么。如果我想启动活动,它会自动停止。下面是我的代码:
private GoogleMap mMap;
LocationManager myLocationManager;
Location myLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pechhulp);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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) {
return;
}
myLocation = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Pak de Latitude en Longtitude van de aangemaakte locatie.
// These variables are returning null
double latitude = myLocation.getLatitude();
double longtitude = myLocation.getLongitude();
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
LatLng myPosition = new LatLng(latitude, longtitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Dit is uw plaats"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
}
下面是错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
https://stackoverflow.com/questions/38295875
复制相似问题