android - 正确获取 ListView 中行的 _id

标签 android sqlite listview simplecursoradapter simpleadapter

我有一个 ListView,它显示了 SQLite 表中的一堆值。首先,我使用 SimpleCursorAdapter 根据来自 SQL 查询的 Cursor 填充 ListView。我改为使用 SimpleAdapter,因为在将数据发送到 ListView 之前,我必须在列表中操作/添加数据。

使用 SimpleCursorAdapter 点击一行后从 ListView 返回的 id 是来自数据库表的正确 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);
}

使用 SimpleCursorAdapter 填充 ListView 的方法如下所示:

  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

生成列表的代码:

  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

时那样自动执行此操作

有没有办法在 ListView 中操作行的 id 以确保它与数据库表中的 _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;
  }
}

最佳答案

这是使用 SimpleAdapter 处理游标的糟糕方法。您应该实现 CursorAdapter。

public class MyCursorAdapter extends CursorAdapter
{
      LayoutInflater inflater;
      public MyCursorAdapter(Context context, Cursor c) {
        super(context, c);
        inflater = LayoutInflater.from(context);
      }

 @Override
          public void bindView(View view, Context context, Cursor cursor) {
            //cursor is already setted to requared position, just get your column
            TextView tv1 = (TextView)view.findViewById(R.id.textView1);
            TextView tv2 = (TextView)view.findViewById(R.id.textView2);
            tv1.setText(cursor.getString(1));
            tv2.setText(cursor.getString(2));
            viev.addOnClickListener(new OnClickListener{
                 public void onClick(View v){
                    ...
                    cursor.getLong(0);
                    ...
                 }
            });       
          }

@Override
      public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return inflater.inflate(R.layout.my_raw_view, parent, false);
      }
    }

不仅仅是在您的 Activity 中将适配器设置为 ListView 。

Cursor cursor = fetchDataAsCursor();
    ListView myListView = (ListView)findViewById(R.id.my_list_view);
    myListView.setAdapter(new MyCursorAdapter(this,cursot));

关于android - 正确获取 ListView 中行的 _id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8758056/

相关文章:

android - Cordova:构建 android hello world 应用程序时出现 ant 错误代码 1

android - 如何在我的应用程序运行时将我的应用程序图标添加到状态栏中?

sqlite - 从Adobe AIR应用程序更新本地sqlite数据库

sql - 将统计信息保存到 sqlite 数据库

sqlite - Yesod/Persistent 中的外键约束?

android - ListView/ExpandableListView setEmptyView() 无效

Android - 使用 BaseAdapter 搜索 ListView 内容

java - 无法解决改造 2.+ 的错误,但在 1.9.0 版中工作正常

java - Android 上的 DriverManager.getConnection() 出现 UnsupportedOperationException

java - 如何在扩展 Activity 的类中更改 ListView 的不同列表项的不同文本颜色?