3

I have an android application which uses listview.Each row consist of ImageView,a TextView and a CheckBox. I want to get selected items from this listview.I used

private void getSelectedItems() {
        List<String>list = new ArrayList<String>();
        try {
            SparseBooleanArray checkedItems = new SparseBooleanArray();
            checkedItems = listView.getCheckedItemPositions();
            if (checkedItems == null) {
                return;
            }
            final int checkedItemsCount = checkedItems.size();
            for (int i = 0; i < checkedItemsCount; ++i) {
                int position = checkedItems.keyAt(i);
                boolean bool = checkedItems.valueAt(position);
                if (bool) {
                   list.add(mainList.get(position));
                }
            }

        } catch (Exception e) {

        }
    }

But i want to set some items as checked with respect to a condition at start up.The checked item obtain only when if the user check/Uncheck an item.No checked item obtain even if the item is set as checked at the start up programmatically.What is the problem here?

Thanks in Advance

Devu Soman
  • 2,246
  • 13
  • 36
  • 57

1 Answers1

3

Do something like this,

ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
myListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                    int position, long arg3) {
                CheckBox cb = (CheckBox) view.findViewById(R.id.yourCheckBox);
                Toast.makeText(getApplicationContext(), "Row " + position + " is checked", Toast.LENGTH_SHORT).show();
                if (cb.isChecked()) {
                    checkedPositions.add(position); // add position of the row
                                                    // when checkbox is checked
                } else {
                    checkedPositions.remove(position); // remove the position when the
                                            // checkbox is unchecked
                    Toast.makeText(getApplicationContext(), "Row " + position + " is unchecked", Toast.LENGTH_SHORT).show();
                }
            }
        });
Srujan Simha
  • 3,637
  • 8
  • 42
  • 59
  • Ok.Here i did not select any item manually.ie,I did not click on listview items.but setting items as checked prgmmatically.Then how could i obtain the checked items? – Devu Soman Feb 27 '13 at 11:40
  • @Srujan Simha There is no need for the else if statement as it means that the checkBox is already checked, use else{...}. Also, this line gives error: cb.remove(position); alternatively edit it to this: checkedPositions.remove(position); . I edited this answer but you don't agree although its needed. – blueware Apr 26 '15 at 06:30
  • Can we get the already checked values and show them in the listview? @Srujan Simha – Partha Chakraborty Dec 03 '15 at 03:23