我有一个ListView
显示 SQLite 表中的一组值。首先,我使用 aSimpleCursorAdapter
来填充ListView
基于 SQL 查询的游标。我改用 aSimpleAdapter
是因为我必须在列表中操作/添加数据,然后才能将其发送到ListView
.
使用敲击一行后SimpleCursorAdapter
返回的idListView
是数据库表中正确的id,但是使用SimpleAdapter
id看起来就像它刚刚生成的一样,ListView
因为它与位置相同。
我的表如下所示:
_id | col1 | col2 | col3
生成光标的方法SimpleCursorAdapter
如下所示:
public Cursor fetchDataAsCursor()
{
return db.query("table_name", new String[] { "_id", "col1", "col2"}, null, null, null, null, null);
}
填写ListView
using的方法SimpleCursorAdapter
如下所示:
private void simpleFillData()
{
Cursor cursor = dbAdapter.fetchDataAsCursor();
startManagingCursor(cursor);
String[] from = new String[] {"col1", "col2"};
int[] to = new int[] {R.id.col1, R.id.col2};
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.list_row, cursor, from, to);
setListAdapter(notes);
}
这很好用,因为在以下方法中返回的 id 是可以的:
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, DetailActivity.class);
i.putExtra("_id", id);
startActivityForResult(i, ACTIVITY_EDIT);
}
现在切换到SimpleAdapter
.
生成的代码List
:
public ArrayList<HashMap<String, Object>> getList()
{
ArrayList <HashMap<String, Object>> list = new ArrayList();
c = fetchDataAsCursor();
c.moveToFirst();
for(int i = 0; i < c.getCount(); i++)
{
HashMap<String, Object> h = new HashMap<String, Object>();
h.put("_id", c.getLong(0));
h.put("col1", c.getString(1));
h.put("col2", c.getString(2));
//This is the extra column
h.put("extra", calculateSomeStuff(c.getString(1), c.getString(2));
list.add(h);
c.moveToNext();
}
return list;
}
然后对于填充的方法ListView
:
private void fillData()
{
ArrayList<HashMap<String, Object>> list = dbAdapter.getList();
String[] from = new String[] {"col1", "col2", "extra"};
int[] to = new int[] {R.id.col1, R.id.col2, R.id.extra};
SimpleAdapter notes = new SimpleAdapter(this, list, R.layout.list_row, from, to);
setListAdapter(notes);
}
在最后一种方法中,ListView
无法获取_id
列表中的值。我猜想它会像使用SimpleCursorAdapter
有没有办法操纵 a 中行的 idListView
以确保它与_id
数据库表中的键具有相同的值?
(所有代码示例都大大简化了)
编辑:
我想到了。我必须创建自己的子类,SimpleAdapter
其中覆盖public long getItemId(int position)
public class MyListAdapter extends SimpleAdapter
{
private final String ID = "_id";
public PunchListAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
{
super(context, data, resource, from, to);
}
@Override
public long getItemId(int position)
{
Object o = getItem(position);
long id = position;
if(o instanceof Map)
{
Map m = (Map)o;
if(m.containsKey(ID))
{
o = m.get(ID);
if(o instanceof Long)
id = (Long)o;
}
}
return id;
}
}