My Android application uses a ListView with simple two-line rows. The list is filled in using simple static data. I am aware of two different solutions for filling in the list in these circumstances:
1) Using a SimpleAdapter with an ArrayList of Maps, where the static data is put into HashMaps.
2) Using a SimpleCursorAdapter with a MatrixCursor, where the static data is added as rows to the MatrixCursor.
Are there any advantages or disadvantages to using either method? For example, is there a performance penalty to either of them? Is one or the other method more generally favoured, and if so, why?
Example
The main Activity of the application is a ListActivity. I fill in the built-in ListView in the onCreate method of the ListActivity.
Consider that I have some static data defined in an array like this:
private static String fruits[][] =
{
{ "Apple", "red" },
{ "Banana", "yellow" },
{ "Coconut", "white" }
};
Using method 1) SimpleAdapter with ArrayList of Maps
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayList of Maps and populate with fruits
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (int i=0; i<fruits.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Fruit", fruits[i][0]);
map.put("Color", fruits[i][1]);
list.add(map);
}
// Create a SimpleAdapter using the ArrayList of Maps,
// which maps the entries Fruit and Color to the Views text1 and text2
String entries[] = { "Fruit", "Color" };
int views[] = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this,
list, android.R.layout.two_line_list_item, entries, views);
// Attach adapter to ListView
setListAdapter(adapter);
}
Using method 2) SimpleCursorAdapter with MatrixCursor
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a MatrixCursor and populate with fruits
String columns[] = { "_id", "Fruit", "Color" };
MatrixCursor cursor = new MatrixCursor(columns);
for (int i=0; i<fruits.length; i++) {
cursor.newRow()
.add(i)
.add(fruits[i][0])
.add(fruits[i][1]);
}
// Create a SimpleCursorAdapter using the MatrixCursor,
// which maps the entries Fruit and Color to the Views text1 and text2
String entries[] = { "Fruit", "Color" };
int views[] = { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.two_line_list_item, cursor, entries, views, 0);
// Attach adapter to ListView
setListAdapter(adapter);
}
Which method is better?