Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove ListView items in Android

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.

like image 441
kavitha Avatar asked Apr 01 '10 06:04

kavitha


1 Answers

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();         }     }); 
like image 113
esharp Avatar answered Sep 23 '22 02:09

esharp