Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all checked items from a ListView?

I've a couple of question I haven't been able to figure out.

I'm trying to get all the checked elements from a ListView but:

  1. If I check and then uncheck an element, it's returned as "checked" by the getCheckedItemPositions() function

  2. I don't know how can I iterate through this:

    SparseBooleanArray checked = list.getCheckedItemPositions(); 
like image 660
sergi Avatar asked Jan 28 '11 18:01

sergi


2 Answers

The other answers using SparseBooleanArray are nearly correct, but they are missing one important thing: SparseBooleanArray.size() will sometimes only return the count of true values. A correct implementation that iterates over all the items of the list is:

SparseBooleanArray checked = list.getCheckedItemPositions();  for (int i = 0; i < list.getAdapter().getCount(); i++) {     if (checked.get(i)) {         // Do something     } } 
like image 53
Jarett Millard Avatar answered Oct 18 '22 14:10

Jarett Millard


I solved my case with this:

public class MyAdapter extends BaseAdapter{     public HashMap<String,String> checked = new HashMap<String,String>(); ....     public void setCheckedItem(int item) {           if (checked.containsKey(String.valueOf(item))){             checked.remove(String.valueOf(item));         }          else {             checked.put(String.valueOf(item), String.valueOf(item));         }     }         public HashMap<String, String> getCheckedItems(){         return checked;     } } 

To set an element is checked:

public class FileBrowser extends Activity implements OnClickListener{         private ListView list;      ...     list.setOnItemClickListener(new OnItemClickListener(){          @Override         public void onItemClick(AdapterView<?> parent, View view, int item,                 long id) {                          BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();                         bla.setCheckedItem(item);                     }     }); 

Then to get the checked items from outside the class..

MyAdapter bAdapter;     Iterator<String> it = bAdapter.getCheckedItems().values().iterator();                     for (int i=0;i<bAdapter.getCheckedItems().size();i++){                         //Do whatever                         bAdapter.getItem(Integer.parseInt(it.next());                     } 

Hope it can help someone.

like image 43
sergi Avatar answered Oct 18 '22 12:10

sergi