Update data in Arrayadapter

Viewed 21588

i have this problem, i have

private ArrayList<CustomItem> items; 
private ArrayAdapter<CustomItem> arrayAdapter;

i show the data present in items, this data i see in listview, now i want to update data and see this new data

if (!items.isEmpty()) {
    items.clear(); // i clear all data
    arrayAdapter.notifyDataSetChanged(); // first change
    items = getNewData();// insert new data and work well
    arrayAdapter.notifyDataSetChanged();  // second change                                      
}

in the first change i see the data are cleaned, but in second change i don't see the new data in listview, i check and the item don't empty

i don't know where is the error, can you help me? best regads Antonio

3 Answers

The ArrayList you created in Activity class is an reference variable, which is holding the same reference to the ArrayList in your Adapter class by passing through the constructor (when you initialize the Adapter object).

However, by executing items = getNewData(), you're assigning a new reference to the items in your Activity class, the reference in your Adapter class remains the same, thus you see no changes on the screen.


It's like this:

personA: the ArrayList object in Activity class

personB: the ArrayList object in Adapter class

PersonA and personB they are both holding a map of USA (separately), and the screen shows personB's map. Then someone replaces the map of personA with another coutry's map. Guess what, the screen still shows USA map.


Instead of changing the reference of items, you should use add(), remove(), clear() or addAll() to modify the items's data then call notifyDataSetChanged().

Related