My Android
app needs to populate the ListView
using the data from an ArrayList
.
I have trouble doing this. Can someone please help me with the code?
You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.). This is what the Android developer guide says: A ListAdapter that manages a ListView backed by an array of arbitrary objects.
Populating the ArrayListUse the add method to append a value to the ArrayList : dynamicArray. add(10); dynamicArray. add(12); dynamicArray.
Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.
The simplest adapter to use is called an ArrayAdapter because the adapter converts an ArrayList of objects into View items loaded into the ListView container.
You need to do it through an ArrayAdapter
which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).
This is what the Android developer guide says:
A
ListAdapter
that manages aListView
backed by an array of arbitrary objects. By default this class expects that the provided resource id references a singleTextView
. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference aTextView
in the larger layout resource.However the
TextView
is referenced, it will be filled with thetoString()
of each object in the array. You can add lists or arrays of custom objects. Override thetoString()
method of your objects to determine what text will be displayed for the item in the list.To use something other than
TextViews
for the array display, for instanceImageViews
, or to have some of data besidestoString()
results fill the views, overridegetView(int, View, ViewGroup)
to return the type of view you want.
So your code should look like:
public class YourActivity extends Activity { private ListView lv; public void onCreate(Bundle saveInstanceState) { setContentView(R.layout.your_layout); lv = (ListView) findViewById(R.id.your_list_view_id); // Instanciating an array list (you don't need to do this, // you already have yours). List<String> your_array_list = new ArrayList<String>(); your_array_list.add("foo"); your_array_list.add("bar"); // This is the array adapter, it takes the context of the activity as a // first parameter, the type of list view as a second parameter and your // array as a third parameter. ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, your_array_list ); lv.setAdapter(arrayAdapter); } }
tutorial
Also look up ArrayAdapter interface:
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With