Remove ListView items in Android

kavitha picture kavitha · Apr 1, 2010 · Viewed 218.4k times · Source

Can somebody please give me an example code of removing all ListView items and replacing with new items?

I tried replacing the adapter items without success. My code is

populateList(){

 results //populated arraylist with strings

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

 listview.setAdapter(adapter);
 adapter.notifyDataSetChanged();
 listview.setOnItemClickListener(this);

}

// now populating list again

repopulateList(){

 results1 //populated arraylist with strings

 ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, results1);

 listview.setAdapter(adapter1);
 adapter1.notifyDataSetChanged();
 listview.setOnItemClickListener(this);
}

Here repopulateList() method will add to ListView items, but it doesn't remove/replace all ListView items.

Answer

esharp picture esharp · Mar 17, 2011

You will want to remove() the item from your adapter object and then just run the notifyDatasetChanged() on the Adapter, any ListViews will (should) recycle and update on it's own.

Here's a brief activity example with AlertDialogs:

adapter = new MyListAdapter(this);
    lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
        adb.setTitle("Delete?");
        adb.setMessage("Are you sure you want to delete " + position);
        final int positionToRemove = position;
        adb.setNegativeButton("Cancel", null);
        adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                MyDataObject.remove(positionToRemove);
                adapter.notifyDataSetChanged();
            }});
        adb.show();
        }
    });