如何覆盖CursorAdapter bindView

Hol*_*olm 5 sqlite android overriding cursor

我正在尝试显示a Cursor中的信息ListView,每行包含a ImageView和a TextView.我有一个CustomCursorAdapter扩展CursorAdapter,在bindView我评估光标数据和基于设置视图图像和文本.

当我运行应用程序时,ListView显示正确的行数,但它们是空的.我知道我在覆盖bindView时遗漏了一些东西,但我不确定是什么.

任何帮助将不胜感激.

private class CustomCursorAdapter extends CursorAdapter {

  public CustomCursorAdapter() {
    super(Lmw.this, monitorsCursor);
  }

  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater layoutInflater = getLayoutInflater();

    return layoutInflater.inflate(R.layout.row, null);
  }

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    try {
      int monitorNameIndex = cursor.getColumnIndexOrThrow(DbAdapter.MONITORS_COLUMN_MONITOR_NAME);
      int resultTotalResponseTimeIndex = cursor.getColumnIndexOrThrow(DbAdapter.RESULTS_COLUMN_TOTAL_RESPONSE_TIME);

      String monitorName = cursor.getString(monitorNameIndex);
      int warningThreshold = cursor.getInt(resultTotalResponseTimeIndex);

      String lbl = monitorName + "\n" + Integer.toString(warningThreshold) + " ms";

      TextView label = (TextView) view.findViewById(R.id.label);     
      label.setText(lbl);

      ImageView icon = (ImageView)view.findViewById(R.id.icon);
      if(warningThreshold < 1000) {
        icon.setImageResource(R.drawable.ok);      
      } else {
        icon.setImageResource(R.drawable.alarm);
      }


    } catch (IllegalArgumentException e) {
      // TODO: handle exception
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Edi*_*Edi 4

方法bindView()看起来还可以。

尝试替换您的newView()方法:

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return mInflater.inflate(R.layout.row, parent, false);
}
Run Code Online (Sandbox Code Playgroud)

并且,出于性能原因:

  • 移动getLayoutInflater()到构造函数中
  • 所有的电话都是一样的cursor.getColumnIndexOrThrow(),正如评论
    中已经说过的那样
  • 使用 StringBuilder 创建lbl文本
  • 无需执行Integer.toString(warningThreshold) ...只需使用warningThreshold

稍后编辑inflate():您的方法与我建议的方法之间的唯一区别是,该方法创建与父级匹配的布局参数。