Search code examples
androidandroid-listviewsimplecursoradapterandroid-viewbinder

Populating listview with images - viewbinder or customcursoradapter? How to?


I'm trying to populate a listview with images, whose URI is returned from a cursor.

I'm not sure if I should use a viewbinder with my simplecursoradapter, or to create a custom simplecursoradapter that somehow does the same job, and I also don't know how to implement either of those options.

My adapter has the following:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.albumitem, albumCursor, displayFields, displayViews);


String[] displayFields = new String[] { AudioColumns.ALBUM,
        AudioColumns.ARTIST, AlbumColumns.NUMBER_OF_SONGS };

int[] displayViews = new int[] { R.id.albumTitle, R.id.artistTitle,
        R.id.totalSongs};

But I'd like to add an image to R.id.albumView as well.

I can obtain the image normally (outside of an adapter) by retrieving the AlbumColumns.ALBUM_ID from the cursor, and then using the following code:

currentAlbumId = idList.get(currentSongIndex);
currentAlbumIdLong = Integer.parseInt(currentAlbumId);
artworkUri = Uri.parse("content://media/external/audio/albumart");
currentSongUri = ContentUris.withAppendedId(artworkUri, currentAlbumIdLong);
albumArt.setImageURI(currentSongUri);

My problem is, I have no idea how to perform a similar task inside the adapter. Anyhow, my best guess is to use a viewBinder. Could somebody kindly show me how to implement this?

Thank you for your help.

--Edit--

Two great answers. Thank you both.


Solution

  • private class YourCustomAdatper extends CursorAdapter{
    
    private final LayoutInflater mInflater;
    
    public YourCustomAdatper(Context context, Cursor cursor) {
    super(context, cursor, true);
    mInflater = LayoutInflater.from(context);
      }
    
    @Override
    public void bindView(View view, Context context, final Cursor cursor)
    {
    ImageView imageview=view.findViewById(yourImageview_id);
    //do rest of task
        }
    
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final View view =mInflater.inflate(yourLayout, parent, false);
    
    return view;
        }
    
    }