kAnNaN
kAnNaN

Reputation: 3679

Select the checked items in a ListView after unchecking one of the CheckBoxes?

I'm trying to get the items that are checked in a ListView. The problem here is that when I try to get the item after I unchecked one, it displays all the elements which are checked and also unchecked. For example, if I check option A, B and C and get the list of checked items, it results 3, then if I try after unchecking option B, I still get the result as 3. Here is my code:

public class ClikableList extends Activity implements OnItemClickListener{
/** Called when the activity is first created. */
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     lv = (ListView) findViewById(R.id.listView1); 
    lv.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, GENRES));
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setOnItemClickListener(this);


}

private static final String[] GENRES = new String[] {
    "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
    "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {

    //Toast.makeText(getBaseContext(),lv.getItemAtPosition(position) + " Test "+lv.getCheckedItemPositions().size(), Toast.LENGTH_SHORT).show();        
        System.out.println(lv.getItemAtPosition(position)); 
    lv.updateViewLayout(arg1, null);

}}

Upvotes: 0

Views: 1021

Answers (2)

Ignacio Parada
Ignacio Parada

Reputation: 11

Are you sure this is working correctly?

Because, as far as I know, you need to use checkedPositions.valueAt(i) in place of checkedPositions.get(i)

Upvotes: 1

user
user

Reputation: 87064

I don't know how you get the checked items but you should use the method getCheckedItemPositions() to get the position checked by the user in the ListView:

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
        SparseBooleanArray checkedPosistions = lv.getCheckedItemPositions(); // this will return a mapping of the position in the adapter and a boolean value
        String results = "";
        int count = lv.getAdapter().getCount();
        for (int i = 0; i < count; i++) {
            if (checkedPositions.get(i)) { //if true this is a checked item
                results += i + ",";
            }
        }
        Toast.makeText(this, "The checked items are :" + results,
                Toast.LENGTH_SHORT).show();
        // ...
}}

Upvotes: 1

Related Questions