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.
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(); } });
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