为什么ItemizeOverlay产生ArrayOutOfBoundException并不总是Occure这个问题?

时间:2012-06-27 12:31:00

标签: android google-maps

我在谷歌地图上显示POI的列表: -

1-用户放大或缩小web服务调用,该调用响应特定位置的xml属性。

2-获取属性后,我们必须过滤具有相同lat,long的属性并在地图上显示气泡上的那些数字(例如3个列表具有相同的lat,将该列表长放入arrayList并显示在气泡3上)。

3-但是当我很少不总是在缩放时出现异常:

  06-27 15:10:57.269: E/AndroidRuntime(4968): FATAL EXCEPTION: main
  06-27 15:10:57.269: E/AndroidRuntime(4968): java.lang.ArrayIndexOutOfBoundsException: index=0 length=0
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at com.google.android.maps.ItemizedOverlay.getIndexToDraw(ItemizedOverlay.java:211)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at com.google.android.maps.ItemizedOverlay.draw(ItemizedOverlay.java:240)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at com.google.android.maps.Overlay.draw(Overlay.java:179)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at com.google.android.maps.MapView.onDraw(MapView.java:530)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.View.draw(View.java:9304)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.drawChild(ViewGroup.java:2586)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.drawChild(ViewGroup.java:2584)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at android.view.ViewGroup.drawChild(ViewGroup.java:2584)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.drawChild(ViewGroup.java:2584)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
  06-27 15:10:57.269: E/AndroidRuntime(4968):   at android.view.ViewGroup.drawChild(ViewGroup.java:2584)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.drawChild(ViewGroup.java:2584)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.View.draw(View.java:9307)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.widget.FrameLayout.draw(FrameLayout.java:419)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2076)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewRoot.draw(ViewRoot.java:1706)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewRoot.performTraversals(ViewRoot.java:1420)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.view.ViewRoot.handleMessage(ViewRoot.java:2066)
 06-27 15:10:57.269: E/AndroidRuntime(4968):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at android.os.Looper.loop(Looper.java:132)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at android.app.ActivityThread.main(ActivityThread.java:4126)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at java.lang.reflect.Method.invokeNative(Native Method)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at java.lang.reflect.Method.invoke(Method.java:491)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
06-27 15:10:57.269: E/AndroidRuntime(4968):     at dalvik.system.NativeStart.main(Native Method)

我正在使用此代码:-`

    mapView.setOnTouchListener(new OnTouchListener() {

private class Mapdatatask extends AsyncTask<Void, Void, Integer> {

    @Override
    protected Integer doInBackground(Void... params) {

        try 
        {
            StringBuilder sb=new StringBuilder();  
            URL sourceUrl=new URL(ListURL);
            System.out.println("----ListURL------"+ListURL);
            InputStream inputStream=sourceUrl.openStream();  
            //add if necessary the PushBack measure to safeguard the intended purpose here if really happening  
            //that you can actually ascertain it by saving a local copy for inspection  
            BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));  
            String line;  
            while ((line=br.readLine())!=null) {  
                sb.append(line+"\n");  
            }  
            br.close(); 

            SAXParserFactory spff=SAXParserFactory.newInstance();
            spff.setNamespaceAware(true); 
            SAXParser spp=spff.newSAXParser();
            XMLReader xr=spp.getXMLReader();
            myHandler=new ApplicationHandler();
            xr.setContentHandler(myHandler);
            xr.parse(new InputSource(new StringReader(sb.toString())));  
            //xr.parse(new InputSource(sourceUrl.openStream()));
            valueoftotal = ApplicationHandler.value;


        }
        catch(IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {

            try 
            {
                StringBuilder sb=new StringBuilder();  
                URL sourceUrl=new URL(ListURL);
                InputStream inputStream=sourceUrl.openStream();  
                //add if necessary the PushBack measure to safeguard the intended purpose here if really happening  
                //that you can actually ascertain it by saving a local copy for inspection  
                BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));  
                String line;  
                while ((line=br.readLine())!=null) {  
                    sb.append(line+"\n");  
                }  
                br.close(); 
                inputStream.close();
                SAXParserFactory spff=SAXParserFactory.newInstance();
                spff.setNamespaceAware(true); 
                SAXParser spp=spff.newSAXParser();
                XMLReader xr=spp.getXMLReader();
                Log.e("ListURL to parse ",""+ListURL);

                myHandler=new ApplicationHandler();
                xr.setContentHandler(myHandler);
                System.out.println(""+sb);
                xr.parse(new InputSource(new StringReader(sb.toString())));  
                //xr.parse(new InputSource(sourceUrl.openStream()));
                valueoftotal = ApplicationHandler.value;
                //arrayList = myHandler.getParsedData();

            }
            catch(IOException e1) {
                e1.printStackTrace();
                Log.e("parse exception0"," dont know why");
                Log.e("XML Error ",e.toString());

        return 1;

    }


    @Override
    protected void onPostExecute(Integer result) 
    {
        if(valueoftotal!=null && !valueoftotal.equalsIgnoreCase(""))
        {
            if(Integer.parseInt(valueoftotal) > 0 && Integer.parseInt(valueoftotal) <= 100)
            {
                OverlayItem oi=null;
                if(myHandler.getParsedData()!=null)
                {
                    ArrayList<Applicationdataset> arrayList = myHandler.getParsedData();
                    //mlist = new ArrayList<Applicationdataset>();
                    myvectorlist = new Vector<ArrayList<Applicationdataset>>();
                    //mlist.addAll(arrayList);
                    System.out.println(arrayList.size()+"++++++++++");
                    Map<Key, ArrayList<Applicationdataset>> mlistVector = groupTheList(arrayList);
                    myvectorlist = putIntoVector(mlistVector);
                    for(int mindex=0;mindex<myvectorlist.size();mindex++)
                    {
                        if(myvectorlist.get(mindex)==null)
                        {
                            myvectorlist.remove(mindex);
                        }
                        if(myvectorlist.get(mindex).size()==0)
                        {
                            myvectorlist.remove(mindex);
                        }
                    }
                }
                linearbottom2.setClickable(true);
                synchronized (oi) {
                    mapOverlays.clear();
                    overlay.removeAll();
                }

                lineartabbar.setBackgroundResource(R.drawable.mapbar);

                if(myvectorlist != null && myvectorlist.size() > 1)
                {
                    Applicationdataset data = null;
                    for(int i = 0; i < myvectorlist.size(); i++)
                    { 
                        {
                            data = myvectorlist.get(i).get(0);
                            String latvalue = data.getLatitude().toString();
                            String lonvalue = data.getLongitude().toString();

                            GeoPoint point = null;
                            try
                            {
                                point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
                            }
                            catch (NumberFormatException e) 
                            {
                            }

                            if(point != null)
                            {
                                oi = overlay.createItem(i);
                                if(overlay!=null)
                                {
                                  if(oi!=null)
                                  {
                                      System.out.println("overlay.size()--"+overlay.size());
                                    if(overlay.size()!=0) 
                                    {
                                        overlay.addItem(oi);

                                        if(myvectorlist.size() == 1)
                                        {
                                            mc.animateTo(point);
                                            mc.setCenter(point);
                                            mc.setZoom(16);
                                        }   
                                    }
                                  }

                                }//end
                            }

                    }

                    System.out.println("+++size of overlay++++"+overlay.size());

                    mapOverlays.add(overlay);

                    mapView.invalidate();
                }


                textViewpopup.setText(valueoftotal+" listings found.");
                linearlayoutpopup.setVisibility(View.VISIBLE);
                RunAnimationslisting();

            }
            else if(Integer.parseInt(valueoftotal) > 100)
            {

                Eyelidmessage(valueoftotal+" listings found. \n Zoom-in, press the locate button below or select the refine button above to display fewer properties. ");
                lineartabbar.setBackgroundResource(R.drawable.mapwithoutlist);
                linearbottom2.setClickable(false);                  

            }
            else if(Integer.parseInt(valueoftotal) == 0)
            {
                GoneAnimations();
                lineartabbar.setBackgroundResource(R.drawable.mapwithoutlist);
                linearbottom2.setClickable(false);
                customizeDialog = new CustomizeDialog(activity);  
                customizeDialog.setTitle("Sorry");  
                customizeDialog.setMessage("No Listing Found");  
                customizeDialog.show();
            }
        }

        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        currenttask = null;
    }

}

private  class GoogleMapViewOverlay extends ItemizedOverlay 
{
    ImageButton bluebutton,savebutton,closebutton;

    ImageThreadLoader imageloader;

    //final MapController mc;
    TextView text1,text2,text3,text4,textup;
    ImageView imageview;

    private PopupPanel panel = new PopupPanel(R.layout.mappopup);
    private Drawable marker;
    private Context mContext;


    public GoogleMapViewOverlay(Drawable drawable, MapView mapView,
            Activity activity2)
    {
        //super(drawable);
        super(boundCenterBottom(drawable));
        setLastFocusedIndex(-1);
        populate();         

        items = new ArrayList<OverlayItem>();
        marker = drawable;
        mContext = mapView.getContext();
        mc = mapView.getController();
        this.activity = activity2;
        DB = new DatabaseHelper(activity2);
    }

    public void removeAll()
    {
        items.clear();
        setLastFocusedIndex(-1);
        populate();
    }       

    @Override
    protected OverlayItem createItem(int index) 
    {
        Projection getcoords;
        GeoPoint point = null;
        int size =0;
        String latvalue="";
        String lonvalue="";
        Point pcon = new Point(0,0);
        getcoords = mapView.getProjection();

        if(myvectorlist!=null)
        {
            if(myvectorlist.size()!=0)
            {
            size = myvectorlist.get(index).size();
            latvalue = myvectorlist.get(index).get(0).getLatitude().toString();
            lonvalue = myvectorlist.get(index).get(0).getLongitude().toString();    
            }
        }

        try
        {
            point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
        }
        catch (NumberFormatException e)
        {
            e.printStackTrace();
        }

        if(getcoords!=null)
        {
            if(point!=null)
            {
                if(pcon!=null)
                {
                    getcoords.toPixels(point, pcon);        
                }                   
            }               
        }

        OverlayItem oi = new OverlayItem(point,"", "");
        if(size == 1)
         {
            boundCenterBottom(drawable);                
            oi.setMarker(drawable);
        }else
        if(size>1) 
        {
            Drawable d= writeOnDrawable(drawable1,size);
            boundCenterBottom(d);//drawable1                
            oi.setMarker(d);//drawable1 
        }


        return oi;
    }

    @Override
    public int size() 
    {
        //Log.e("","items.size()"+items.size());
        if (items != null && items.size() > 0)
            return items.size();
        else 
            return 0;       
    }

    public void addItem(OverlayItem item) 
    {
        System.out.println("adddoverlayitem "+items+"\titem"+item);
        try {

            items.add(item);
            setLastFocusedIndex(-1);
            populate();
        } catch (NullPointerException e) {

            e.printStackTrace();
        }
    }

class PopupPanel
  {
    // View popup;
     PopupPanel(int layout)
       {
        ViewGroup parent=(ViewGroup)mapView.getParent();
        popup = getLayoutInflater().inflate(layout, parent, false);
        }
    View getView() {
        return(popup);
    }

    void show(boolean alignTop)
    {
        popup.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );

        if (alignTop) 
        {
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);            

            lp.setMargins(65, 100, 0, 0);

        }
        else
        {
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            lp.setMargins(0, 0, 0, 60);
        }

        hide();

        ((ViewGroup)mapView.getParent()).addView(popup, lp);            

        isVisible=true;

    }

    void hide() {

        if (isVisible)
        {
            isVisible=false;
            ((ViewGroup)popup.getParent()).removeView(popup);
        }
    }
}

public void Eyelidmessage(String message)
{
    textViewpopup.setText(message);
    linearlayoutpopup.setVisibility(View.VISIBLE);              
    RunAnimations();
}

private void RunAnimationslisting() {

    Animation a;
    a = AnimationUtils.loadAnimation(this, R.anim.translate);
    a.reset();

    linearlayoutpopup.clearAnimation();
    a.setFillAfter(true);
    linearlayoutpopup.startAnimation(a);

    a.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationEnd(Animation animation) {
            System.out.println("@@doneanimation listner works 1@@");

            try {
                Thread.sleep(2000);
                GoneAnimationslisting();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationStart(Animation animation) {

        }

    });

}

private void GoneAnimationslisting() {

    Animation a1;
    a1 = AnimationUtils.loadAnimation(this, R.anim.translate1);
    a1.reset();

    linearlayoutpopup.clearAnimation();
    a1.setFillAfter(true);
    linearlayoutpopup.startAnimation(a1);


    a1.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationEnd(Animation animation) {
            System.out.println("@@doneanimation listner works 1@@");

            linearlayoutpopup.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationStart(Animation animation) {

        }
    });
}

private Drawable writeOnDrawable(Drawable objdrawable, int size)
 {
    String text = ""+size;
    Bitmap bitmap = ((BitmapDrawable)objdrawable).getBitmap().copy(Bitmap.Config.ARGB_8888, true);

    Paint paint = new Paint(); 
    paint.setStyle(Style.FILL);  
    paint.setColor(Color.WHITE); 
    paint.setTypeface((Typeface.defaultFromStyle(Typeface.BOLD)));
    paint.setTextSize(20);
    float txtwidth = paint.measureText(text);

    Canvas canvas = new Canvas(bitmap);

   // canvas.drawText(text, 0, , paint);
    canvas.drawText(text,((bitmap.getWidth()/2)-(txtwidth/2)),bitmap.getHeight()/2, paint);

    Drawable d =new BitmapDrawable(getResources(),bitmap);
    return d;
}


private Map<Key, ArrayList<Applicationdataset>> groupTheList(ArrayList<Applicationdataset> arrayList) {
    Map<Key, ArrayList<Applicationdataset>> map = new HashMap<Key, ArrayList<Applicationdataset>>();
    for (Applicationdataset appSet : arrayList) {
        Key key = new Key(appSet.getLatitude(), appSet.getLongitude());
        ArrayList<Applicationdataset> list = map.get(key);
        if (list == null) {
            list = new ArrayList<Applicationdataset>();
            map.put(key, list);
        }
        list.add(appSet);
    }
    return map;
}

public class Key {
    String _lat;
    String _lon;

    Key(String lat, String lon) {
        _lat = lat.trim();
        _lon = lon.trim();
    }

    @Override
    public boolean equals(Object o) {
        //if (this == o) return true;
       // if (o == null || getClass() != o.getClass()) return false;

        //Key key = (Key) o;

        //if (!_lat.equals(key._lat)) return false;
        //if (!_lon.equals(key._lon)) return false;
        return o instanceof Key
        && (_lat.equals(((Key)o)._lat))
        && (_lon.equals(((Key)o)._lon));


        //return true;
    }

    @Override
    public int hashCode() {

        return _lat.hashCode() + _lon.hashCode();

    }
}

private Vector<ArrayList<Applicationdataset>> putIntoVector(Map<Key, ArrayList<Applicationdataset>> myMap)
 {
    Vector<ArrayList<Applicationdataset>> mvectorlist = new Vector<ArrayList<Applicationdataset>>();
    Iterator<Entry<Key, ArrayList<Applicationdataset>>> miterator = myMap.entrySet().iterator();
    while (miterator.hasNext()) {
        Map.Entry<Key, ArrayList<Applicationdataset>> pairs = (Map.Entry<Key, ArrayList<Applicationdataset>>)miterator.next();
        mvectorlist.add(pairs.getValue());
        miterator.remove(); // avoids a ConcurrentModificationException
    }

    return mvectorlist;

}
}

任何人帮助我,我无法解决这个问题,直到现在大约10个小时我一直在花钱看到这个..

3 个答案:

答案 0 :(得分:3)

java.lang.ArrayIndexOutOfBoundsException: index=0 length=0表示您在大小为零时尝试访问ArrayList的元素。返回代码并确保您没有尝试访问空列表。

编辑:

好的,我想我知道你的问题是什么。我认为您正在使用createItem尝试为您的ItemizedOverlay添加叠加层。此功能命名不佳,实际上并不创建项目。它只是从OverlayItems数组中返回一个项目。您需要使用GoogleMapViewOverlay.addOverlay(OverlayItem)向地图添加OverlayItem。尝试使用随机坐标创建几个测试叠加层,看看是否有效。请务必停止使用createItem()并开始使用addItem()。如果这不是您的问题,请发布您的所有代码,也许我们可以帮助您更好一点。

答案 1 :(得分:0)

我不确定您的代码中出现错误的位置,但您可以尝试更改:

if (size == 1) {
} else {
}

为:

if (size == 1) {
} else if (size > 1) {
}

这可能会消除你的ArrayIndexOutOfBoundsException

答案 2 :(得分:0)

花了更多时间后,由于这篇文章,我已经达到了我的问题: - Async Task throw ConCurrent Modification Exception?