问题
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
回答1:
Assuming the getNewData() function returns ArrayList<CustomItem>
, can you change the line:
items=getNewData();
to
items.addAll(getNewData());
and see if that works?
回答2:
This is how I update the Adapter with new data:
if (arrayAdapter == null) {
arrayAdapter = new CustomArrayAdapter(getActivity(), data);
listview.setAdapter(userAutoCompleteAdapter);
} else {
arrayAdapter.clear();
arrayAdapter.addAll(newData);
arrayAdapter.notifyDataSetChanged();
}
回答3:
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()
.
来源:https://stackoverflow.com/questions/11658758/update-data-in-arrayadapter