Android:为什么方法 getLatitude() 和 getLongtitude() return 为空?

Android: Why does de methods getLatitude() and getLongtitude() return null?

我正在尝试为一个位置获取 2 个变量,但它 returns 为空。 我不知道我做错了什么。如果我想启动 activity 它 自行停止。这是我的代码:

 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

您必须检查权限块,因为 myLocations 始终为空。在调用 getLatitude()getLongitude().

之前先调用 onRequestPermissionsResult

请检查:Requesting Permissions at Run Time