这是我的自定义简单游标适配器:
public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, int flags) {
super(context, layout, c, from, to, 0);
this.mContext = context;
mInflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.row, parent, false);
return view;
}
@Override
public void bindView(View view, Context context, Cursor c) {
TextView rowView = (TextView) view.findViewById(R.id.row);
ImageView rowImg = (ImageView) view.findViewById(R.id.img);
String img = null;
String row = null;
if (c != null) {
img = c.getString(c.getColumnIndex(Db.TABLE_IMG));
row = c.getString(c.getColumnIndex(Db.TABLE_TITLE));
}
if (img != null) rowImg.setImageResource(R.drawable.smiley);
else img.setImageResource(0);
rowView.setText(row);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] from = new String[] { ... };
int[] to = new int[] { ... };
...
getLoaderManager().initLoader(0, null, this);
mAdapter = new MySimpleCursorAdapter(this, R.layout.row, null, from,
to, 0);
setListAdapter(mAdapter);
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { Db.TABLE_ID,
Db.TABLE_TITLE };
CursorLoader c = new CursorLoader(this,
MyProvider.CONTENT_URI, projection, null, null, null);
return c;
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
填充ListView时出错:
java.lang.IllegalStateException:无法从CursorWindow读取第0行col -1。在从中访问数据之前,请确保Cursor已正确初始化。
答案 0 :(得分:1)
您的投影{Db.TABLE_ID,Db.TABLE_TITLE}与您尝试检索Db.TABLE_IMG和Db.TABLE_TITLE的值不同。由于在尝试通过适配器访问Db.TABLE_IMG时没有查询它,因此它不存在(这会引发错误)。更改您的预测以包含Db.TABLE_IMG,该错误应该消失