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 a SparseBooleanArray to get the checked items and then delete the same and refresh listview.
public class MainActivity extends Activity
{
ListView lv;
ArrayAdapter<String> adapter;
Button delete;
ArrayList<String> data = new ArrayList<String>();
SparseBooleanArray mCheckStates ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
lv = (ListView)findViewById(R.id.listView1);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
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)
{
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < lv.getCount(); i++){
if (checked.get(i)==true)
{
data.remove(i);
}
adapter.notifyDataSetChanged();
}
lv.clearChoices();
}
});
}
}
Edit:
Try the below
delete.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
SparseBooleanArray checkedItemPositions = lv.getCheckedItemPositions();
int itemCount = lv.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(data.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With