sandee
sandee

Reputation: 349

WHY ItemizeOverlay produce ArrayOutOfBoundException Not Always Occure This issue?

I am showing POI's List on google map as:-

1- User Zoom-In or Zoom-Out a webservice call which responce xml of properties in perticular location.

2- After getting property we have to filter those properties which have same lat,long and show those number on bubbles on map(say 3 list have same lat ,long put that list into a arrayList and show on bubbles 3).

3- but when I seldom not always I am zooming map following Exception occurs:

  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)

And I am using This code:-`

    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;

}
}

Anyone help me I unable to solve this issue till now near about 10 hours I have been spends plaese see this..

Upvotes: 0

Views: 443

Answers (3)

sandee
sandee

Reputation: 349

After spend more time I have reach that My problem due to this post:- Async Task throw ConCurrent Modification Exception?

Upvotes: 0

crocboy
crocboy

Reputation: 414

java.lang.ArrayIndexOutOfBoundsException: index=0 length=0 means that you are trying to access an element of an ArrayList when the size is zero. Go back through your code and make sure you're not trying to access an empty list.

EDIT:

Okay, I think I know what you're problem is. I think you're using createItem to try and add overlays to your ItemizedOverlay. This function is poorly named, and does not actually create an item. It simply returns an item from your array of OverlayItems. You need to use GoogleMapViewOverlay.addOverlay(OverlayItem) to truly add an OverlayItem to the map. Try creating a couple test Overlays with random coordinates and see if that works out. Remember to stop using createItem() and start using addItem(). If this isn't your problem then post all of of your code and maybe we can help you out a little better.

Upvotes: 3

Jimbali
Jimbali

Reputation: 2538

I'm not sure at what point in your code the error is arising, but you could try changing:

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

to:

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

That might get rid of your ArrayIndexOutOfBoundsException

Upvotes: 0

Related Questions