2016-03-24 47 views
-2

即时创建一个小的移动应用程序,应该让我能够在谷歌地图上找到我目前的位置。 我让它工作得更早,我可以点击其中一个按钮,它放大到我当前的位置。 现在,由于某种原因,即时得到以下错误Location.getLongitude()null object reference

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

它朝我的代码53行指出这是下面贴:

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

} 

53号线是指:double myLongitude = myLocation.getLongitude();

不知道为什么这发生了 任何帮助将不胜感激!

回答

0

locationManager.getLastKnownLocation(provider)可以返回null,如文档here中所述。

在你的代码中,你得到一个NullPointerException,因为在第53行中,myLocation为空。

相关问题