触摸覆盖项时触发空指针异常

时间:2012-11-24 13:04:53

标签: android google-maps overlayitem

嘿,我是Android的新手在这里我正在使用一个面向地图的项目现在我遇到了一个问题,当我触摸覆盖项时它显示在log-cat中的空指针异常我无法理解它是什么意思。在这里我有两个类MyPlacemapActivity和AddItemizedOverlay有人请帮我解决这个问题,这里是我的班级代码

AddItemizedOverlay.java

public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {

       private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();

       private Context context;
       String reference;
       private String username;

       String p_u_name;
       public AddItemizedOverlay(Drawable defaultMarker) {
            super(boundCenterBottom(defaultMarker));
       }

       public AddItemizedOverlay(Drawable defaultMarker, Context context) {
            this(defaultMarker);
            this.context = context;
       }

       public AddItemizedOverlay(Drawable defaultMarker, Context context,String StringData) {
                   this(defaultMarker);
                   this.context = context;
       this.username=StringData;
       System.out.println("AdditemizedOverlay:got username:"+username +StringData);
              }


       @Override
       public boolean onTouchEvent(MotionEvent event, MapView mapView)
       {   
               if (event.getAction() == 1) {
               GeoPoint geopoint = mapView.getProjection().fromPixels(
                   (int) event.getX(),
                   (int) event.getY());
           }
           return false;
       } 

       @Override
       protected OverlayItem createItem(int i) {
          return mapOverlays.get(i);
       }
       @Override
       public int size() {
          return mapOverlays.size();
       }

      @Override
       protected boolean onTap(int index) {
         OverlayItem item = mapOverlays.get(index);
         AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
         reference = item.getSnippet();
         username =  item.getTitle();
         dialog.setTitle("");
         dialog.setMessage("Do you want ot park here ?");
         System.out.println("Inside Additemized:"+reference+username);
         dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {


                SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
                SharedPreferences.Editor editor =prefs.edit();
                editor.putString("KEY_REFERENCE", reference);
                editor.putString("KEY_USERNAME", username);
                editor.commit();                

                Intent intent = new Intent(context, SinglePlaceActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
         })
            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
//                  MainActivity.this.finish();
                }
            });
         dialog.show();
         return true;
       }

       public void addOverlay(OverlayItem overlay) {
          mapOverlays.add(overlay);
       }

       public void populateNow(){
           this.populate();
       }

    }

MyPlacemapActivity.java

public class MyPlacemapActivity extends MapActivity {
    // Nearest places
    PlacesList nearPlaces;

    // Map view
    MapView mapView;

    // Map overlay items
    List<Overlay> mapOverlays;

    AddItemizedOverlay itemizedOverlay;
    MyItemizedOverlay myitemizedoverlay;
    FindItemizedOverlay finditemizedoverlay;

    GeoPoint geoPoint;
    // Map controllers
    MapController mc;

    Drawable defaultMarker,drawable;

    double latitude;
    double longitude;
    OverlayItem overlayitem;

    String p_u_name;
    String type,keyword;

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

        SharedPreferences prefs = getSharedPreferences("myprefs", 0);
        p_u_name = prefs.getString("KEY_USERNAME", "");

        Intent i = getIntent();

        // Users current geo location
        String user_latitude = i.getStringExtra("user_latitude");
        String user_longitude = i.getStringExtra("user_longitude");
        type = i.getExtras().getString("KEY_TYPES");
        keyword =i.getExtras().getString("KEY_KEYWORD");

        System.out.println("sarath"+user_latitude + user_longitude + type);

        // Nearplaces list
        nearPlaces = (PlacesList) i.getSerializableExtra("near_places");

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

        mapOverlays = mapView.getOverlays();

        // Geopoint to place on map
        geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),(int) (Double.parseDouble(user_longitude) * 1E6));

        // Drawable marker icon
        Drawable drawable_user = this.getResources().getDrawable(R.drawable.mark_red);

        myitemizedoverlay = new MyItemizedOverlay(drawable_user, this);

        // Map overlay item
        overlayitem = new OverlayItem(geoPoint, "Your Location","That is you!");

        myitemizedoverlay.addOverlay(overlayitem);

        mapOverlays.add(myitemizedoverlay);
        myitemizedoverlay.populateNow();

        System.out.println("keyword:"+keyword+"type:"+type);
//----------------------------------------------------------------------------------------------------------        
        // Drawable marker icon
        if(type.equalsIgnoreCase("gas_station")&&keyword.equalsIgnoreCase("gas_station")){
             drawable= this.getResources().getDrawable(R.drawable.mark_gasstation);
             finditemizedoverlay = new FindItemizedOverlay(drawable);

        mc = mapView.getController();

        // These values are used to get map boundary area
        // The area where you can see all the markers on screen
        int minLat = Integer.MAX_VALUE;
        int minLong = Integer.MAX_VALUE;
        int maxLat = Integer.MIN_VALUE;
        int maxLong = Integer.MIN_VALUE;

        // check for null in case it is null
        if (nearPlaces.results != null) {


            // loop through all the places
            for (Place mplace : nearPlaces.results) {

                latitude = mplace.geometry.location.lat; // latitude
                longitude = mplace.geometry.location.lng; // longitude

                // Geopoint to place on map
                geoPoint = new GeoPoint((int) (latitude * 1E6),
                        (int) (longitude * 1E6));

                // Map overlay item
                overlayitem = new OverlayItem(geoPoint,p_u_name,mplace.reference);

                finditemizedoverlay.addOverlay(overlayitem);

                // calculating map boundary area
                minLat  = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
                minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
                maxLat  = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
                maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
            }
            mapOverlays.add(finditemizedoverlay);

            // showing all overlay items
            finditemizedoverlay.populateNow();
        }


        // Adjusting the zoom level so that you can see all the markers on map
        mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));

        // Showing the center of the map
        mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
        mapView.postInvalidate();
        }

        else if(type.equalsIgnoreCase("shopping_mall")&&keyword.equalsIgnoreCase("shopping_mall")){
            drawable= this.getResources().getDrawable(R.drawable.mark_shopping);
             finditemizedoverlay = new FindItemizedOverlay(drawable);

        mc = mapView.getController();

        // These values are used to get map boundary area
        // The area where you can see all the markers on screen
        int minLat = Integer.MAX_VALUE;
        int minLong = Integer.MAX_VALUE;
        int maxLat = Integer.MIN_VALUE;
        int maxLong = Integer.MIN_VALUE;

        // check for null in case it is null
        if (nearPlaces.results != null) {


            // loop through all the places
            for (Place mplace : nearPlaces.results) {

                latitude = mplace.geometry.location.lat; // latitude
                longitude = mplace.geometry.location.lng; // longitude

                // Geopoint to place on map
                geoPoint = new GeoPoint((int) (latitude * 1E6),
                        (int) (longitude * 1E6));

                // Map overlay item
                overlayitem = new OverlayItem(geoPoint,p_u_name,mplace.reference);

                finditemizedoverlay.addOverlay(overlayitem);

                // calculating map boundary area
                minLat  = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
                minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
                maxLat  = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
                maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
            }
            mapOverlays.add(finditemizedoverlay);

            // showing all overlay items
            finditemizedoverlay.populateNow();
        }


        // Adjusting the zoom level so that you can see all the markers on map
        mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));

        // Showing the center of the map
        mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
        mapView.postInvalidate();
        }

    else if(type.equalsIgnoreCase("restaurant")&&keyword.equalsIgnoreCase("restaurant")){
        drawable= this.getResources().getDrawable(R.drawable.mark_restaurant_blue);
         finditemizedoverlay = new FindItemizedOverlay(drawable);

    mc = mapView.getController();

    // These values are used to get map boundary area
    // The area where you can see all the markers on screen
    int minLat = Integer.MAX_VALUE;
    int minLong = Integer.MAX_VALUE;
    int maxLat = Integer.MIN_VALUE;
    int maxLong = Integer.MIN_VALUE;

    // check for null in case it is null
    if (nearPlaces.results != null) {


        // loop through all the places
        for (Place mplace : nearPlaces.results) {

            latitude = mplace.geometry.location.lat; // latitude
            longitude = mplace.geometry.location.lng; // longitude

            // Geopoint to place on map
            geoPoint = new GeoPoint((int) (latitude * 1E6),
                    (int) (longitude * 1E6));

            // Map overlay item
            overlayitem = new OverlayItem(geoPoint,p_u_name,mplace.reference);

            finditemizedoverlay.addOverlay(overlayitem);

            // calculating map boundary area
            minLat  = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
            minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
            maxLat  = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
            maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
        }
        mapOverlays.add(finditemizedoverlay);

        // showing all overlay items
        finditemizedoverlay.populateNow();
    }


    // Adjusting the zoom level so that you can see all the markers on map
    mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));

    // Showing the center of the map
    mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
    mapView.postInvalidate();
    }

    else if(type.equalsIgnoreCase("parking")&&keyword.equalsIgnoreCase("garage parking")){
        drawable= this.getResources().getDrawable(R.drawable.mark_blue);
         itemizedOverlay = new AddItemizedOverlay(drawable);

    mc = mapView.getController();

    // These values are used to get map boundary area
    // The area where you can see all the markers on screen
    int minLat = Integer.MAX_VALUE;
    int minLong = Integer.MAX_VALUE;
    int maxLat = Integer.MIN_VALUE;
    int maxLong = Integer.MIN_VALUE;

    // check for null in case it is null
    if (nearPlaces.results != null) {


        // loop through all the places
        for (Place mplace : nearPlaces.results) {

            latitude = mplace.geometry.location.lat; // latitude
            longitude = mplace.geometry.location.lng; // longitude

            // Geopoint to place on map
            geoPoint = new GeoPoint((int) (latitude * 1E6),
                    (int) (longitude * 1E6));

            // Map overlay item
            overlayitem = new OverlayItem(geoPoint,p_u_name,mplace.reference);

            System.out.println("inside mymap:"+mplace.reference+p_u_name);

            itemizedOverlay.addOverlay(overlayitem);

            // calculating map boundary area
            minLat  = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
            minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
            maxLat  = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
            maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
        }
        mapOverlays.add(itemizedOverlay);

        // showing all overlay items
        itemizedOverlay.populateNow();
    }


    // Adjusting the zoom level so that you can see all the markers on map
    mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));

    // Showing the center of the map
    mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
    mapView.postInvalidate();
    }
    else if(type.equalsIgnoreCase("parking")&&keyword.equalsIgnoreCase("street parking")){
        drawable= this.getResources().getDrawable(R.drawable.mark_blue);
         itemizedOverlay = new AddItemizedOverlay(drawable);

    mc = mapView.getController();

    // These values are used to get map boundary area
    // The area where you can see all the markers on screen
    int minLat = Integer.MAX_VALUE;
    int minLong = Integer.MAX_VALUE;
    int maxLat = Integer.MIN_VALUE;
    int maxLong = Integer.MIN_VALUE;

    // check for null in case it is null
    if (nearPlaces.results != null) {


        // loop through all the places
        for (Place mplace : nearPlaces.results) {

            latitude = mplace.geometry.location.lat; // latitude
            longitude = mplace.geometry.location.lng; // longitude

            // Geopoint to place on map
            geoPoint = new GeoPoint((int) (latitude * 1E6),
                    (int) (longitude * 1E6));

            // Map overlay item
            overlayitem = new OverlayItem(geoPoint,p_u_name,mplace.reference);

            System.out.println("inside mymap:"+mplace.reference +p_u_name);

            itemizedOverlay.addOverlay(overlayitem);

            // calculating map boundary area
            minLat  = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
            minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
            maxLat  = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
            maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
        }
        mapOverlays.add(itemizedOverlay);

        // showing all overlay items
        itemizedOverlay.populateNow();
    }


    // Adjusting the zoom level so that you can see all the markers on map
    mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));

    // Showing the center of the map
    mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
    mapView.postInvalidate();
    }
    else
    {
         AlertDialog.Builder builder = new AlertDialog.Builder(MyPlacemapActivity.this);
           builder.setTitle("Connection Error.");
           builder.setMessage("Try again?.")  
                  .setCancelable(false)
                  .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int id) {
                          Intent u = new Intent(getApplicationContext(),Find_TabActivity.class);
                          startActivity(u);
                        dialog.dismiss();
                      }
                  });                     
           AlertDialog alert = builder.create();
           alert.show();    
    }
    }

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

}

1 个答案:

答案 0 :(得分:2)

问题出在以下几行:

finditemizedoverlay = new FindItemizedOverlay(drawable);

您正在初始化ItemizedOverlay而未传递onTap()方法创建AletDialo所需的上下文。

您应该将其替换为:

finditemizedoverlay = new FindItemizedOverlay(drawable, this);

Note:如果你把logcat放在你的问题中会有所帮助。

问候。