Hi i am stuck with deleting multiple items from listview using checkbox. I am able to select multiple items from listview but only the first item that is selected, is getting deleted while other items are not being deleted. Here is my code. Thanks in Advance!
public class MainActivity extends Activity
{
ListView lv;
ArrayAdapter<String> adapter;
Button delete;
ArrayList<String> data = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.listView1);
delete = (Button)findViewById(R.id.button1);
data.add("Windows");
data.add("Android");
data.add("Apple");
data.add("Blackberry");
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, data);
lv.setAdapter(adapter);
delete.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
deleteCheckedItems();
adapter.notifyDataSetChanged();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void deleteCheckedItems() {
int count = adapter.getCount();
for (int i = 0; i < count; i++)
{
if (lv.isItemChecked(i))
{
data.remove(i);
}
}
}
}
Use
removeAll
fordata
and pass an array of elements to be deleted to the method. The reson is this:for example you have 10 elements, after the 4th element deleted, all indexes 5-9 are moved to 4-8, thus your cycle is not correct because you use
old
indexes.Maybe you should try code below. The code is based on recurrency. After the "OnClick" event the Bremselected is called. The ListView is iterated until the "checked" checkbox is founded. Then item is removed and another time (there is recurrency) the Bremselected is called and the new iteration begins from scratch with the "size" decremented.
}
Use a SparseBooleanArray to get the checked items and then delete the same and refresh listview.
Edit:
Try the below