地图视图获取覆盖物时出现空指针异常。

3

大家好,我正在尝试在我的谷歌地图上实现一个覆盖层。然而,在运行时我收到了一个致命错误,似乎是某种NullPointerException。当我删除代码中的“overlayList = mapView.getOverlays();”和“overlayList.add(t);”这两行时,应用程序可以正常运行。非常感谢任何帮助!

主活动:

public class CSActivity extends MapActivity implements LocationListener  {

 MapController mapController;
 MapView mapView;
 LocationManager locationManager;

MyLocationOverlay myLocationOverlay;
MyLocationOverlay compass;

private Button click_but;
private Button exit_but;
long start;
long stop;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
String towers;
int lat;
int lng;

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.main); // bind the layout to the activity

    click_but = new Button(this);
    click_but = (Button)findViewById(R.id.clickBtn);
    exit_but = new Button(this);
    exit_but = (Button)findViewById(R.id.exitBtn);

    d = getResources().getDrawable(R.drawable.markerblue);
    Touchy t = new Touchy();

    overlayList = mapView.getOverlays();
    overlayList.add(t);
    /*compass = new MyLocationOverlay(CSActivity.this, mapView);
    overlayList.add(compass);*/


    // Configure the Map
    mapView = (MapView) findViewById(R.id.mapView);
    mapView.setBuiltInZoomControls(true);
    mapView.setSatellite(true);
    mapController = mapView.getController();
    mapController.setZoom(20); // Zoom 1 is world view
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);



    myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);


    Criteria crit = new Criteria();
    towers = locationManager.getBestProvider(crit, false);
    Location L = locationManager.getLastKnownLocation(towers);
    if (L != null){
        lat = (int) (L.getLatitude()*1E6);
        lng = (int) (L.getLongitude()*1E6);

        GeoPoint ourLocation = new GeoPoint(lat, lng);
        OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
        MyItemizedOverlay custom = new MyItemizedOverlay(d, CSActivity.this);
        custom.insertPinpoint(overlayItem);
        overlayList.add(custom);
    }else{
        Toast.makeText(CSActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
    }




    final CSActivity home = this;   

    exit_but.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) 
        {
            Intent intent = new Intent();
            intent.setClass(home, homeActivity.class);
            startActivity(intent);

        }

    });

    click_but.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) 
        {


        }

    });









}

@Override
protected boolean isRouteDisplayed() {
    return false;
}



@Override
protected void onResume() {
    super.onResume();
    myLocationOverlay.enableMyLocation();
    myLocationOverlay.enableCompass();
    locationManager.requestLocationUpdates(towers, 500, 1, this);

}

@Override
protected void onPause() {
    super.onResume();
    myLocationOverlay.disableMyLocation();
    myLocationOverlay.disableCompass();
    locationManager.removeUpdates(this);
}

class Touchy extends Overlay {
    public boolean onTouchEvent(MotionEvent e, MapView m){
        if (e.getAction() == MotionEvent.ACTION_DOWN){
            start = e.getEventTime();
            x = (int) e.getX();
            y = (int) e.getY();
             touchedPoint = mapView.getProjection().fromPixels(x, y);
        }
        if (e.getAction() == MotionEvent.ACTION_UP){
            stop = e.getEventTime();
        }
        if (stop - start > 1000){
            //Perform action
            AlertDialog alert = new AlertDialog.Builder(CSActivity.this).create();
            alert.setTitle("Pick an Option");
            alert.setMessage("I said pick!");
            alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    OverlayItem overlayItem = new OverlayItem(touchedPoint, "What's up", "2nd String");
                    MyItemizedOverlay custom = new MyItemizedOverlay(d, CSActivity.this);
                    custom.insertPinpoint(overlayItem);
                    overlayList.add(custom);
                }
            });

    alert.setButton2("get address", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
                    try{
                        List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
                    if (address.size() > 0){
                        String display = "";
                        for (int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){

                            display += address.get(0).getAddressLine(i) + "\n";
                        }
                        Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                        t.show();
                    }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally{

                    }
                }
            });
            alert.show();
            return true;

        }


        return false;
    }
}










@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    lat = (int) (location.getLatitude() *1E6);
    lng = (int) (location.getLongitude()*1E6);

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
}

项目化覆盖活动:

   public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem>  {

private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>(); 
private Context c;

public MyItemizedOverlay(Drawable defaultMarker) {
    super(boundCenter(defaultMarker));
    // TODO Auto-generated constructor stub
}

public MyItemizedOverlay(Drawable m, Context context) {
    // TODO Auto-generated constructor stub
    this(m);
    c = context;
}

@Override
protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return pinpoints.get(i);
}

@Override
public int size() {
    // TODO Auto-generated method stub
    return pinpoints.size();
}

public void insertPinpoint(OverlayItem item) {
    pinpoints.add(item);
    this.populate();
}

}

主XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >

<com.google.android.maps.MapView
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:apiKey="(key here)"
    android:clickable="true"
    android:enabled="true" />

<Button
    android:id="@+id/clickBtn"
    style="@style/ButtonText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:background="@drawable/blue"
    android:text="Click" />

<Button
    android:id="@+id/exitBtn"
    style="@style/ButtonText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/red"
    android:text="Home" />

</RelativeLayout>
2个回答

5

mapView为空,因此会出现NPE 首先从xml文件中获取引用

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

然后获取叠加层。
overlayList = mapView.getOverlays();

并且

if(null!=overlayList&&overlayList.size()!=0){
overlayList.add(t);
}

Why NullPointerException ?


@downvoter,能否说一下为什么要点踩?我完全不同意...这个回答有什么问题吗? - Samir Mangroliya

1

在定义MapView之前,您正在获取地图覆盖层,因此会出现空指针异常。

所以先定义mapview控件,然后再使用它。

 mapView = (MapView) findViewById(R.id.mapView);
overlayList = mapView.getOverlays();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接