繁体   English   中英

空指针异常

[英]Nullpointer Exception

我有以下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;
 } 

 }
}

我看到了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);

(我不喜欢Java中的'out'参数,toPixels将为您创建点对象并返回它)

好的,似乎从未引用过公共属性GeoPoint p,因此在null上指向pointint。 也许您想在此行中定义p:

GeoPoint point =新的GeoPoint(geoLat.intValue(),geoLng.intValue());

您应该找到分配p的正确位置,然后问题已解决。

您需要保留对myMapView的引用,以后将使用它。 完成此操作的方法是使用strong属性将其声明为属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM