Remove ListView items in Android
Asked Answered
H

12

63

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.

Hovel answered 1/4, 2010 at 6:44 Comment(0)
B
80

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();
        }
    });
Belicia answered 17/3, 2011 at 20:37 Comment(1)
MyDataObject would be whatever your ultimate backing store is. Most of the time, you don't just want to remove items from being DISPLAYED, you also want to remove them from some database, or some server, or some file storage. Esharp was just leaving a reminder that you need to remember to really delete the data, in addition to removing it from display.Koski
R
26

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

Rianon answered 3/11, 2010 at 6:51 Comment(0)
R
19

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

Remote answered 1/4, 2010 at 7:51 Comment(1)
There is no clear() for my CustomAdapter that extends from BaseAdapter!Forensic
P
15
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
 adapter.remove(adapter.getItem(i));
}

then call notifyDataSetChanged();

Primine answered 17/1, 2012 at 10:55 Comment(5)
Should be adapter.remove(adapter.getItem(0));?Vignette
adapter.remove(adapter.getItem(0)); this will only remove the first element but if you want to remove all of them then go for what i have posted..Primine
Ishtar's comment is correct. The above code will attempt to remove items past the end of the list. Each iteration through the list removes one item, so by the time i is equal to (count - 1), you have a one-item list and getItem(i) will fail.Supplication
you can simply items from end to start in this way: for (int i = count-1; i >= 0; i--) { adapter.remove(adapter.getItem(i)); }Favus
IndexOutOfRange approaching.Dessiedessma
Z
10

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

m_adapter.remove(o);
m_adapter.notifyDataSetChanged();
Zettazeugma answered 25/11, 2011 at 22:44 Comment(0)
A
4
            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.

Ailis answered 17/3, 2011 at 5:28 Comment(0)
P
4
  • 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();
}
Paz answered 28/8, 2013 at 14:54 Comment(0)
G
3

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();
  }
}
Gerry answered 29/5, 2015 at 2:46 Comment(0)
A
1

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

    });

}
Armanda answered 25/1, 2015 at 14:21 Comment(0)
D
1

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

 yourCollection.clear();
 setListAdapter(null);
Danielledaniels answered 6/3, 2015 at 11:57 Comment(0)
G
1

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;
        }
    });
Glamour answered 28/10, 2019 at 13:16 Comment(0)
C
0

Try this:

String text = ( (TextView) view).getText().toString();<br>
adapter.remove(text);

enter image description here

Claro answered 14/9, 2021 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.