2016-03-24 7 views
-2

Im Erstellen einer kleinen mobilen App, die es mir erlauben sollte, meinen aktuellen Standort auf Google Maps zu finden. Ich hatte es funktioniert früher konnte ich auf einen der Knöpfe klicken und es gezoomt in meine aktuelle Position. Jetzt aus irgendeinem Grund imLocation.getLongitude() null Objektreferenz

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

es deutet auf Linie 53 von meinem Code den folgenden Fehler bekommen, die unten geschrieben wird:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 

    private GoogleMap mMap; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // 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); 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 

     mMap.getUiSettings().setZoomControlsEnabled(true); 
     mMap.setMyLocationEnabled(true); 

     // Get LocationManager object from System Service LOCATION_SERVICE 
     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     // Create a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 

     // Get the name of the best provider 
     String provider = locationManager.getBestProvider(criteria, true); 

     // Get Current Location 
     Location myLocation = locationManager.getLastKnownLocation(provider); 

     double myLongitude = myLocation.getLongitude(); 
     double myLatitude = myLocation.getLatitude(); 

     // Create a LatLng object for the current location 
     LatLng latLng = new LatLng(myLongitude, myLatitude); 

     Marker me = mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(myLatitude, myLongitude)) 
       .title("Im here!") 
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.people)) 
     ); 
     // Zoom into my current location 
     mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myLatitude, myLongitude), 15.0f)); 
    } 

} 

Linie 53 bezieht sich auf: double myLongitude = myLocation.getLongitude();

Keine Ahnung, warum dies geschieht Jede Hilfe wird geschätzt!

Antwort

0

locationManager.getLastKnownLocation(provider) kann Null zurückgeben, wie in der Dokumentation here beschrieben. In Ihrem Code erhalten Sie eine NullPointerException, weil in Zeile 53 myLocation null ist

Verwandte Themen