Search code examples
androidandroid-listviewarraylistandroid-arrayadaptermultichoiceitems

android multichoice listview error Exception


for choosing favorite contact ,i load all contact inside a list view and declare my adapter like below :

ArrayAdapter<String> cnct_List_Adapter =new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_multiple_choice,info);

and for show result i use this codes :

            try 
            {
                SparseBooleanArray a = LvPopupContacts.getCheckedItemPositions();
                String my_sel_items="";
                for(int i = 0; i < LvPopupContacts.getCount() ; i++)
                {
                    if (a.valueAt(i))
                    {
                     /*
                        Long val = lView.getAdapter().getItemId(a.keyAt(i));
                        Log.v("MyData", "index=" + val.toString()
                             + "item value="+lView.getAdapter().getItem(i));
                        list.add(lView.getAdapter().getItemId((a.keyAt(i))));
                     */

                        my_sel_items = my_sel_items + "," 
                            + (String) LvPopupContacts.getAdapter().getItem(i);
                    }
                }
                Toast.makeText(getActivity(),String.valueOf(a.size()), 0).show();
                Log.v("Contacts :" ,my_sel_items);
            } catch (Exception e) {
                   Log.v("e Error" ,e.toString());
            }

now , when i use this in emulator it work rightly , but when it test in Device return e Exception

Exception: java.lang.ArrayindexOutOfBoundsException length=13;index=13

remember , my Device have about 220 concacts.


Solution

  • your bug is here:

       for(int i = 0; i < LvPopupContacts.getCount() ; i++)
    

    "a" array contains all of checked items but you loop over all LvPopupContacts so change it to

      for(int i = 0; i < a.size() ; i++)