我有一个List,每个条目都有一个动态的属性计数,应该显示出来。一行中的每个属性都有一个名称和一个值。这种实现有效,但我怎么能以更有效的方式做到这一点?到现在为止,我需要在非常费时的事情之前建立整个列表/地图......:
// get category names
Map<Long, String> categoriesNames = new HashMap<Long, String>();
// ...
// create log-list of maps for SimpleAdapter
List<Map<String, String>> logsMap = new ArrayList<Map<String, String>>();
// getAll() is just: db.query(true, TABLE_NAME, null, null, null, null, null, Columns.TIMESTAMP + " desc", null);
Cursor logs = logDao.getAll();
try {
int idIndex = logs.getColumnIndex("_id");
int timestampIndex = logs.getColumnIndex("timestamp");
int categoryIdIndex = logs.getColumnIndex("category_id");
int noteIndex = logs.getColumnIndex("note");
while (logs.moveToNext()) {
Map<String, String> map = new HashMap<String, String>();
map.put("category", categoriesNames.get(logs.getLong(categoryIdIndex)));
map.put("note", getString(R.string.note) + ": " + logs.getString(noteIndex));
map.put("timestamp", MyDateUtils.formatDateTime(logs.getLong(timestampIndex)));
map.put("attributes", attributeLogDao.getAttributesAndValuesByLogId(logs.getLong(idIndex)));
logsMap.add(map);
}
} finally {
logs.close();
}
// Mapping
String[] from = new String[] { "category", "note", "timestamp", "attributes" };
int[] to = new int[] {
R.id.log_list_row_category, R.id.log_list_row_note,
R.id.log_list_row_datetime, R.id.log_list_row_attributes };
// ListView Adapter
SimpleAdapter simpleAdapter = new SimpleAdapter(this,
logsMap, R.layout.log_list_row, from, to);
ListView lv = (ListView) this.findViewById(R.id.listView);
lv.setAdapter(simpleAdapter);
到目前为止,我正在构建一个使用simpleAdapter的列表。我不知道如何使用CursorAdapter左右,因为这行:
map.put("attributes", attributeLogDao.getAttributesAndValuesByLogId(logs.getLong(idIndex)));
(在while循环中几乎是最后一行)
这个电话的作用是:
public String getAttributesAndValuesByLogId(long logId) {
String attributesString = "";
Cursor c = db.getSQLiteDatabase().rawQuery("SELECT al." + Columns.VALUE + " AS value, a." + AttributeDao.Columns.NAME + " AS a_name" +
" FROM " + TABLE_NAME + " AS al, " + AttributeDao.TABLE_NAME + " AS a" +
" WHERE al." + Columns.LOG_ID + " = " + logId +
" AND a." + AttributeDao.Columns.ID + " = al." + Columns.ATTRIBUTE_ID +
" ORDER BY value DESC", null);
if (c != null && c.moveToFirst()) {
do {
attributesString += c.getString(1) + " (" + c.getLong(0) + ")\n";
} while (c.moveToNext());
c.close();
}
return attributesString;
}
谢谢!
答案 0 :(得分:1)
指向写入方向:
SimpleCursorAdapter
,保留大部分代码。SimpleCursorAdapter.ViewBinder
,需要一种方法setViewValue。setViewValue
的实施方式几乎与您while
循环的当前正文相同。SimpleCursorAdapter#setViewBinder
链接两者。视图绑定器的目的是让您有机会自定义列的影响方式。 setViewValue
的实现类似于:
if (columnIndex == categoryIdIndex) {
... populate view with category name ...
return true;
}
if (columnIndex == timestampIndex) {
...