3

こんにちは、Google マップにオーバーレイを実装しようとしています。ただし、実行時に致命的なエラーが発生し、ある種の 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>
4

2 に答える 2

5

mapView is null so get NPE最初にxmlファイルからの参照を与える

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

次にオーバーレイを取得します

overlayList = mapView.getOverlays();

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

NullPointerException の理由

于 2012-06-05T08:39:24.723 に答える
1

MapView を定義する前に MapView のオーバーレイを取得しているため、null ポインターが期待されます。

そのため、最初に mapview コントロールを定義してから使用します。

 mapView = (MapView) findViewById(R.id.mapView);
overlayList = mapView.getOverlays();
于 2012-06-05T08:42:59.657 に答える