下面的代碼有什麼問題。它在這條線上拋出空指針異常(location.setLatitude(latitude);
)。我試圖在應用程序啓動後立即創建一個圓,這是我從onCreate
方法傳遞位置對象的原因。GeoPoint中的空指針異常
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);
這裏有什麼問題嗎?
您沒有傳遞任何位置的物體在這片碼。你在別的地方設置位置嗎?如果不是的話,這很明顯爲什麼location == null。也許你只是忘了向LocationManager詢問最後一個已知的位置並設置它的位置? – Tobold
位置'在給定的代碼段中從不初始化。初始化它。 –
我在我的問題的代碼中添加了更多信息。我不確定我完全理解你們的意見。我的目標是在應用程序啓動後畫一個Circle,這就是我從'onCreate方法'傳遞初始位置的原因。任何人都可以從代碼的角度來解釋我。 – ferhan