即时创建一个小型移动应用,应该可以让我在谷歌地图上找到我当前的位置。 我让它早些时候工作,我能够点击其中一个按钮,它放大到我当前的位置。 现在由于某种原因我得到以下错误
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 :(得分:0)
locationManager.getLastKnownLocation(provider)
可以返回null,如文档here中所述。
在您的代码中,您获得的是NullPointerException
,因为在第53行中,myLocation
为空。