I'm trying to use a SimpleCursorAdapter
with a ViewBinder
to get an image from the database and put it into my ListView
item view. Here is my code:
private void setUpViews() {
mNewsView = (ListView) findViewById(R.id.news_list);
Cursor cursor = getNews();
SimpleCursorAdapter curAdapter = new SimpleCursorAdapter(
getApplicationContext(), R.layout.cursor_item, cursor,
new String[] { "title", "content", "image" },
new int[] { R.id.cursor_title, R.id.cursor_content,
R.id.news_image });
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
ImageView image = (ImageView) view;
byte[] byteArr = cursor.getBlob(columnIndex);
image.setImageBitmap(BitmapFactory.decodeByteArray(byteArr, 0, byteArr.length));
return true;
}
};
ImageView image = (ImageView) findViewById(R.id.news_image);
viewBinder.setViewValue(image, cursor, cursor.getColumnIndex("image"));
curAdapter.setViewBinder(viewBinder);
mNewsView.setAdapter(curAdapter);
}
I am getting:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 60
while executing byte[] byteArr = cursor.getBlob(columnIndex);
. Does anyone have an idea what am I doing wrong?
I think the cursor.moveToFirst()
has not been called so the cursor is throwing android.database.CursorIndexOutOfBoundsException.
Before using a cursor
you should always check is the cursor is empty or not by calling cursor.moveToFirst()
. This will also position the cursor at the first position.