0
我想獲取2個變量的位置,但它返回null。 我不知道我在做什麼錯。如果我想開始活動,它自己停止。這裏是我的代碼:Android:爲什麼get方法getLatitude()和getLongtitude()返回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