Исключение нулевого указателя - PullRequest
0 голосов
/ 20 августа 2010

У меня есть следующее MapOverlay.Следующая строка выдает NullPointer, но я не понимаю, почему: S mapView.getProjection().toPixels(p, screenPts); Кто-нибудь может мне помочь?

    public class Mapview extends MapActivity {
GeoPoint p;
MapView mapView; 
MapController mc;

@Override
protected boolean isRouteDisplayed() {
 return false;
}
public int icount = 0;
MapController mapController;
MyPositionOverlay positionOverlay;
private LocationData tweets;
public int start = 0;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);



MapView myMapView = (MapView)findViewById(R.id.mapView);

myMapView.setSatellite(true);
myMapView.setStreetView(true);
myMapView.displayZoomControls(false);
mapController = myMapView.getController();

mapController.setZoom(17);
myMapView.setBuiltInZoomControls(true);

//Adding points here


//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = myMapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);        

myMapView.invalidate();

// Add the MyPositionOverlay
positionOverlay = new MyPositionOverlay();
List<Overlay> overlays = myMapView.getOverlays();
overlays.add(positionOverlay);


LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);


locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);

}


private final LocationListener locationListener = new LocationListener() {
 public void onLocationChanged(Location location) {
  updateWithNewLocation(location);
}

public void onProviderDisabled(String provider){
  updateWithNewLocation(null);
}

public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status, 
                            Bundle extras){ }
 };

private void updateWithNewLocation(Location location) {
String latLongString ="";
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";

if (location != null) {
     // Update my location marker
    positionOverlay.setLocation(location);

  // Update the map location.
  Double geoLat = location.getLatitude()*1E6;
  Double geoLng = location.getLongitude()*1E6;
  GeoPoint point = new GeoPoint(geoLat.intValue(), 
                                geoLng.intValue());

  mapController.animateTo(point);

  double lat = location.getLatitude();
  double lng = location.getLongitude();
  latLongString = "Lat:" + lat + "\nLong:" + lng;
  Global.lat = lat;
  Global.lng = lng;
  double latitude = location.getLatitude();
  double longitude = location.getLongitude();

  Geocoder gc = new Geocoder(this, Locale.getDefault());
  try {
    List<Address> addresses = gc.getFromLocation(latitude, 
                                                 longitude, 1);
    StringBuilder sb = new StringBuilder();
    if (addresses.size() > 0) {
      Address address = addresses.get(0);

      for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
        sb.append(address.getAddressLine(i)).append("\n");

        sb.append(address.getLocality()).append("\n");
        sb.append(address.getPostalCode()).append("\n");
        sb.append(address.getCountryName());
    }
    addressString = sb.toString();
  } catch (IOException e) {}
} else {
  latLongString = "No location found";
}
}

class MapOverlay extends com.google.android.maps.Overlay
{
  @Override
  public boolean draw(Canvas canvas, MapView mapView, 
  boolean shadow, long when) 
  {
      super.draw(canvas, mapView, shadow);                   

      //---translate the GeoPoint to screen pixels---
      Point screenPts = new Point();
      mapView.getProjection().toPixels(p, screenPts);

      //---add the marker---
      Bitmap bmp = BitmapFactory.decodeResource(
          getResources(), R.drawable.marker);            
      canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
      return true;
 } 

 }
}

Ответы [ 3 ]

2 голосов
/ 20 августа 2010

Я вижу объявление GeoPoint p, но нет выражения, где p фактически инициализировано.Таким образом, передача null методу toPixels() может быть причиной для NPE.

Вместо этого попробуйте этот код, чтобы проверить, нет ли NPE:

  //---translate the GeoPoint to screen pixels---
  if (p == null) return false;
  Point screenPts = mapView.getProjection().toPixels(p, null);

(Мне не нравятся параметры out в Java, toPixels создаст для вас точечный объект и вернет его)

0 голосов
/ 03 сентября 2015

Вам необходимо сохранить ссылку на myMapView, которую вы будете использовать позже.Способ сделать это - объявить его как свойство, используя атрибут strong.

0 голосов
/ 30 мая 2012

Хорошо, кажется, что на публичный атрибут GeoPoint p никогда не ссылаются, поэтому pointint на null.Возможно, вы хотите определить p в этой строке:

Точка GeoPoint = новая GeoPoint (geoLat.intValue (), geoLng.intValue ());

Вы должны найти место для назначения p, то проблема исправлена.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...