I need to use an ArrayAdapter to populate a ListView in my Android application. In order to use the ArrayAdapter, it says
For example, if you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array:
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, myStringArray);
The arguments for this constructor are:
- Your app Context
- The layout that contains a TextView for each string in the array
- The string array
Then simply call setAdapter() on your ListView:
ListView listView = (ListView) findViewById(R.id.listview); listView.setAdapter(adapter);
However, I do not have an array of strings, I have an array of objects that contain string values.
public class Headers {
private String from;
private String to;
private String subject;
public Headers (String from, String to, String subject){
this.from = from;
this.to = to;
this.subject = subject;
}
public String getFrom() { return from; }
public void setFrom(String from) { this.from = from; }
public String getTo() { return to; }
public void setTo(String to) { this.to = to; }
public String getSubject() { return subject; }
public void setSubject(String subject) { this.subject = subject; }
}
My layout does contain a TextView corresponding to values in my object.
Here is my layout with my ListView:
<LinearLayout android:orientation="vertical">
<ListView android:id="@+id/listOfHeaders" >
</LinearLayout>
And here is the layout for each row in the ListView to be populated by the ArrayAdapter:
<LinearLayout android:orientation="horizontal">
<TextView android:id="@+id/toTextView" />
<TextView android:id="@+id/fromTextView" />
<TextView android:id="@+id/subjectTextView" />
</LinearLayout>
ArrayAdapter<Headers>, and notArrayAdapter<String>getViewmethod and do all the mappings (it is easier if you useArrayAdapter(Context context, int resource, int textViewResourceId)ctor)