下面的代码有什么问题。它在这一行(location.setLatitude(latitude);
)上抛出空指针异常。我试图在应用程序启动后立即制作一个圆圈,这就是我从我的onCreate
方法传递位置对象的原因。
private Location location;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
listView = (ListView) findViewById(R.id.mylist);
mapView.setStreetView(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(15);
GeoPoint initialPoint = new GeoPoint( (int) (36.778261* 1E6), (int) (-119.417932 * 1E6));
double latitude = initialPoint .getLatitudeE6() / 1E6;
double longitude = initialPoint .getLongitudeE6() / 1E6;
location.setLatitude(latitude);
location.setLongitude(longitude);
locationListener.onLocationChanged(location);
}
下面是处理 LocationUpdate 的类。
private class GPSLocationListener implements LocationListener {
MapOverlay mapOverlay;
public GPSLocationListener(MapView mapView) {
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(15);
if (mapOverlay == null) {
mapOverlay = new MapOverlay(this,android.R.drawable.star_on);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.add(mapOverlay);
}
mapOverlay.setPointToDraw(point);
mapView.invalidate();
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
任何建议都会有很大帮助。
更新:-
做出改变后,我得到了
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
下面是我进行更改的代码。
GeoPoint initialPoint = new GeoPoint( (int) (36.778261), (int) (-119.417932));
double latitude = initialPoint .getLatitudeE6() / 1E6;
double longitude = initialPoint .getLongitudeE6() / 1E6;
this.location = new Location("TechGeeky Randomly Initialized");
location.setLatitude(latitude);
location.setLongitude(longitude);
locationListener.onLocationChanged(location);
我在这里做错了什么吗?