I’m trying update a ListView with an entirely new ArrayList. For API 11 it works great using the addAll(…) method, but this is not available for earlier APIs. I can’t figure out how to go about updating an entire list like this for older versions.
ArrayAdapter<String> textList = new ArrayAdapter<String>(listener, R.layout.list_item, stringList);
listener.setListAdapter(textList);
Then later…
textList.clear();
textList.addAll(stringList); <--- works fine for Android 3.0 (API Level 11) and beyond, but not before.
How did you go about doing this before addAll() was introduced in API 11? Thanks.
The simplest way is avoid using ArrayAdapter.addAll() and ArrayAdapter.add() within a loop, like idiottiger suggested in his answer.
If you insist to use ArrayAdapter.addAll(), The short answer is DIY. Check out the source of android.widget.ArrayAdapter here, the actual implementation is much simpler than you thought. there are many alternatives to achieve this, for instance:
android.widget.BaseAdapter, you get full control of private instance
variable and method and can define whatever method your want in your
own implementation. there are many tutorial on the internet tells how
to create custom adapter, like here and here.
android.widget.ArrayAdapter, then add the required public method
addAll() to your own ArrayAdapter implementation, you don’t have the
visibility on private member in android.widget.ArrayAdapter so need
use existing public API ArrayAdapter.add() to add every single
element within a loop.
Option 1 is preferred and used very commonly, especially in the situation when you need render more complex custom UI stuff within your ListView.