-5 years ago 130
Android Question

Getting all of the items from an ArrayAdapter

I have a

backed by an
that gets populated by a
. When the user clicks on one of the items, I want to pass a reference to the selected item, as well as the rest of the list items to another fragment. My question is how should I get all of the items from the adapter? Here are the possibilities that I see:

1. Keep a reference to the backing

Create the adapter like so:

List<DomainObject> items = new ArrayList<DomainObject>();
listAdapter = new ArrayAdapter<DomainObject>(getActivity(), R.layout.mine, items);

and then simply pass
or a copy of it to the next activity.

The downside I see of this is that I'm relying on the undocumented fact that the same list that I pass to the constructor contains the items later on.

2. Iterate through the adapter

When an item is clicked, iterate through the adapter and build up the list. This seems like an unnecessary amount of work. The items are contained in a
in the adapter and I'm manually copying each item to a new list.

3. Keep a separate list of items when adding to adapter

Before adding an item to the adapter, add it to a separate list that I maintain in the fragment. This is also wasteful as the list of items is copied in the
and the fragment.

Answer Source

The solution that I've gone with in the meantime is just to not use ArrayAdapter. In cases where you're fighting against this API, it seems like it's better just to use the less fully-featured (and complex) BaseAdapter. You can read more about the decision to go with BaseAdapter instead of ArrayAdapter in this article: Android Adapter Good Practices.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download