Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I am trying to make a listview with checkbox using listview's built in checkbox method. I have gone through a stackoverflow post and i found it is running properly except one problem.

If there are four items in list and assume, i checked the second and third item, onclicking, it is displaying the second and third item as needed..but if i am selecting first and then third and then second item, and then i m unchecking the first, so i must be left with second and third as desired output. But it is providing first second and third item as output.

can anybody guide me on that..?

This is the java code:

public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{

    Button btn1;
    ListView mListView;
    String[] array = new String[] {"Ham", "Turkey", "Bread"};

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tailoredtwo);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);

        mListView = (ListView) findViewById(R.id.listViewcity);
        mListView.setAdapter(adapter);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
        button.setOnClickListener(this);
    }

    public void onClick(View view) {
        SparseBooleanArray positions = mListView.getCheckedItemPositions();
        int size = positions.size();
        for(int index = 0; index < size; index++) {
            Toast.makeText(getApplicationContext(), array[positions.keyAt(index)].toString(), Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
}
share|improve this question

1 Answer 1

up vote 0 down vote accepted

Change your onClick to

Delcare the below as a class variable

StringBuilder builder;

Then

public void onClick(View view) {
    SparseBooleanArray positions = mListView.getCheckedItemPositions();
    builder = new StringBuilder();
    for(int index = 0; index <array.length; index++) {
         if(positions.get(index)==true)
         {
             builder.append(array[index]);
             builder.append("\n");
         }

    }
    Toast.makeText(getApplicationContext(),builder, Toast.LENGTH_LONG).show();
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.