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 a :
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?
Contact List using ListView and SimpleCusrorAdapter with Contact Photos and Filter/Search
I had been looking for a simpler solution and my final solution is quite closer to the one Daniel mentioned here so I thought I should share mine here. I am using Fragment to show Device Contacts as a list of names with their pictures. Result is pretty similar to that of Daniel's but is showing only names. More information can be shown very easily once you understand the code.
In my case I was fetching names and pictures from ContactsContract using PHOTO_URI so I didn't have to extend
SimpleCursorAdapter
as Daniel had to.My example also includes filtering the list of contacts as user types in
SearchView
to find a contactI have a Fragment called
FragmentContacts
and two Layout files, first the main Layoutfrag_contacts.xml
and second for each contact rowlist_row_contact
.frag_contacts.xml
list_row_contact.xml
FragmentContacts.java
I extended SimpleCursorAdapter, and while I did not use a ViewBinder here is my code for using an image stored as a blob in an sqlite database in a listview. This was adapted from an article I read here.
My layout file for a row is:
row_layout_two_line.xml
The calling code
ImageCursorAdapter.java
}
Here is what it looks like in the end
I think the
cursor.moveToFirst()
has not been called so the cursor is throwingandroid.database.CursorIndexOutOfBoundsException.
Before using a
cursor
you should always check is the cursor is empty or not by callingcursor.moveToFirst()
. This will also position the cursor at the first position.