Remove ListView items in Android

AndroidAndroid Listview

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

I think if u add the following code, it will work

listview.invalidateViews();

To remove an item, Just remove that item from the arraylist that we passed to the adapter and do listview.invalidateViews();
This will refresh the listview

Solution 3 - Android

You can use

adapter.clear() 

that will remove all item of your first adapter then you could either set another adapter or reuse the adapter and add the items to the old adapter. If you use

adapter.add()

to add data to your list you don't need to call notifyDataSetChanged

Solution 4 - Android

int count = adapter.getCount();
for (int i = 0; i < count; i++) {
 adapter.remove(adapter.getItem(i));
}

then call notifyDataSetChanged();

Solution 5 - Android

Remove it from the adapter and then notify the arrayadapter that data set has changed.

m_adapter.remove(o);
m_adapter.notifyDataSetChanged();

Solution 6 - Android

			names = db.getSites();
			la = new ArrayAdapter<String>(EditSiteList.this,
					android.R.layout.simple_list_item_1, names);
			EditSiteList.this.setListAdapter(la);
			listview.invalidateViews();

this code works fine for me.

Solution 7 - Android

  • You should use only one adapter binded with the list of data you need to list
  • When you need to remove and replace all items, you have to clear all items from data-list using "list.clear()" and then add new data using "list.addAll(List)"

here an example:

List<String> myList = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,       android.R.layout.simple_list_item_1, myList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);

populateList(){
   List<String> result = getDataMethods();
   
   myList.addAll(result);
   adapter.notifyDataSetChanged();
}

repopulateList(){
   List<String> result = getDataMethods();
   
   myList.clear();
   myList.addAll(result);
   adapter.notifyDataSetChanged();
}

Solution 8 - Android

Try this code, it works for me.

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_third);
	 String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
		        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
		        "Linux", "OS/2" };
	 liste = new ArrayList<String>();
	 Collections.addAll(liste, values);
	 adapter = new ArrayAdapter<String>(this,
		        android.R.layout.simple_list_item_1, liste);
	 setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
	 liste.remove(position);
	 adapter.notifyDataSetChanged();
  }
}

Solution 9 - Android

At first you should remove the item from your list. Later you may empty your adapter and refill it with new list.

private void add(final List<Track> trackList) {
	MyAdapter bindingData = new MyAdapter(MyActivity.this, trackList);

	list = (ListView) findViewById(R.id.my_list); // TODO

	list.setAdapter(bindingData);


	// Click event for single list row
	list.setOnItemClickListener(new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			// ShowPlacePref(places, position);
			AlertDialog.Builder showPlace = new AlertDialog.Builder(
					Favoriler.this);
			showPlace.setMessage("Remove from list?");
			showPlace.setPositiveButton("DELETE", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {	
				
					trackList.remove(position); //FIRST OF ALL REMOVE ITEM FROM LIST
					list.setAdapter(null); // THEN EMPTY YOUR ADAPTER

					add(trackList); // AT LAST REFILL YOUR LISTVIEW (Recursively)

				}

			});
			showPlace.setNegativeButton("CANCEL", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			showPlace.show();
		}

	});

}

Solution 10 - Android

It's simple .First you should clear your collection and after clear list like this code :

 yourCollection.clear();
 setListAdapter(null);

Solution 11 - Android

You can also use listView.setOnItemLongClickListener to delete selected item. Below is the code.

// listView = name of your ListView

  listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int 
        position, long id) {

        // it will get the position of selected item from the ListView

final int selected_item = position;

            new AlertDialog.Builder(MainActivity.this).
                    setIcon(android.R.drawable.ic_delete)
                    .setTitle("Are you sure...")
                    .setMessage("Do you want to delete the selected item..?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            list.remove(selected_item);
                            arrayAdapter.notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton("No" , null).show();

            return true;
        }
    });

Solution 12 - Android

//try this:

String text = ( (TextView) view).getText().toString();
adapter.remove(text); enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkavithaView Question on Stackoverflow
Solution 1 - AndroidesharpView Answer on Stackoverflow
Solution 2 - AndroidLabeeb PanampullanView Answer on Stackoverflow
Solution 3 - AndroidJanuszView Answer on Stackoverflow
Solution 4 - AndroidRexView Answer on Stackoverflow
Solution 5 - AndroidAtmaView Answer on Stackoverflow
Solution 6 - Androiduser590849View Answer on Stackoverflow
Solution 7 - AndroidHatemTmiView Answer on Stackoverflow
Solution 8 - AndroidNadhir TitaouineView Answer on Stackoverflow
Solution 9 - AndroidMuzaffer Onur DAĞHANView Answer on Stackoverflow
Solution 10 - AndroidzheekView Answer on Stackoverflow
Solution 11 - AndroidM. KHALIL NAZIRView Answer on Stackoverflow
Solution 12 - AndroidAbhinav PandeyView Answer on Stackoverflow