Reputation: 8021
I have a listview with an adapter that receives an ArrayList
in its constructor. The ArrayList
is allocated to an internal variable - like so:
ArrayList<Someobject> mylist;
constructor(ArrayList<Someobject> inputList) {
this.mylist = inputList;
}
Then I use this ArrayList
in the getView()
method to build up my list widget using the viewholder pattern. The question is - when I use adapter.clear()
or adapter.addAll(somenewArray)
- how does the adapter know to replace my adapter's ArrayList
variable with the new one or to clear it? As far as I can make out - it doesn't. My getview()
looks like this:
public View getView(final int position, View convertView, ViewGroup parent) {
...
setValueTo(mylist.get(position));
}
and the variable "mylist" always stays the same no matter what I pass into addAll()
. I feel like I'm missing something basic in the way that this mechanism operates - can anyone help me figure out what?
I originally thought that the adapter would be destroyed and recreated automatically every time addAll()
was called (and therefore its internal arraylist would change), but the constructor is never called again after initial creation.
Is the correct way to solve this to override addAll()
and perform a manual operation of:
this.mylist = newlist;
?
Upvotes: 1
Views: 2891
Reputation: 770
I think after you call to add all you can call notifyDataSetChanged() from your adapter. I will should trigger a refresh to the list view attached to it.
See what documentation says about it.
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
In this case your list view should be among the obervers.
Upvotes: 0
Reputation: 3020
Use the notifyDataSetChanged()
For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.
like
inputList.add(..);
adapter.notifyDataSetChanged();
Upvotes: 2
Reputation: 8629
When using ArrayAdpater
, the List is already "included" for you, you don't need to maintain a separate one. You can think of it as both your collection and your adapter.
Add items to your adapter like this
adapter.add(item);
or
adapter.addAll(collection);
and to obtain the item at a given position :
adapter.getItem(position);
Upvotes: 1
Reputation: 1699
You shouldn't have your own list member in the adapter. The ArrayAdapter itself holds the list of items. Once you work with the different methods in the adapter (get, add, etc.) everything will work as expected.
Your getView()
should look like this:
public View getView(final int position, View convertView, ViewGroup parent) {
....
setValueTo(getItem(position));
}
Upvotes: 1