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 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);
}
}