[ACCEPTED]-update listview dynamically with adapter-listview

Accepted answer
Score: 140

Use a ArrayAdapter backed by an ArrayList. To change 2 the data, just update the data in the list 1 and call adapter.notifyDataSetChanged().

Score: 26

If you create your own adapter, there is 5 one notable abstract function:

public void registerDataSetObserver(DataSetObserver observer) {
    ...
}

You can use 4 the given observers to notify the system 3 to update:

private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();

public void registerDataSetObserver(DataSetObserver observer) {
    observers.add(observer);
}
public void notifyDataSetChanged(){
    for (DataSetObserver observer: observers) {
        observer.onChanged();
    }
}

Though aren't you glad there are 2 things like the SimpleAdapter and ArrayAdapter 1 and you don't have to do all that?

Score: 4

SimpleListAdapter's are primarily used for 5 static data! If you want to handle dynamic 4 data, you're better off working with an 3 ArrayAdapter, ListAdapter or with a CursorAdapter if your data is coming in 2 from the database.

Here's a useful tutorial in understanding binding data in a ListAdapter

As referenced 1 in this SO question

Score: 0

Most people recommend using notifyDataSetChanged(), but I found 4 this link pretty useful. In fact using clear and add you 3 can accomplish the same goal using less 2 memory footprint, and more responsibe app.

For 1 example:

notesListAdapter.clear();
notes = new ArrayList<Note>();
notesListAdapter.add(todayNote);
if (birthdayNote != null) notesListAdapter.add(birthdayNote);

/* no need to refresh, let the adaptor do its job */
Score: 0

I created a method just for that. I use 5 it any time I need to manually update a 4 ListView. Hopefully this gives you an idea of how 3 to implement your own

public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{    
    if(ListVw != null)
    {
        final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();

        //You'll have to create this method in your adapter class. It's a simple setter.
        adapter.SetList(SomeObjects);

        adapter.notifyDataSetChanged();
    }
}

I'm using an adapter 2 that inherites from BaseAdapter. Should work for any 1 other type of adapter.

Score: 0

add and remove methods are easier to use. They update 2 the data in the list and call notifyDataSetChanged 1 in background.

Sample code:

adapter.add("your object");
adapter.remove("your object");

More Related questions