1

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

    }
}

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.