2016-07-10 5 views
0

Ich versuche, 2 Variablen für eine Position zu erhalten, aber es gibt null zurück. Ich weiß nicht, was ich falsch mache. Wenn ich die Aktivität starten möchte, stoppt sie selbst . Hier ist mein Code:Android: Warum geben die Methoden getLatitude() und getLongtitude() null zurück?

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)); 
} 

Und hier ist der Fehler:

                    java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 

Antwort

1

Sie haben die Erlaubnis Block zu überprüfen, weil myLocations immer null ist. Rufen Sie onRequestPermissionsResult bevor Sie getLatitude() und getLongitude() anrufen.

Bitte überprüfen Sie dies: Requesting Permissions at Run Time

Verwandte Themen