Thursday, November 3, 2011

Simple cursor adapter made easy

Here is how to use the CursorAdapter in Android.

In this example, we are gonna draw a list, using the CursorAdapter, for the cursor pointing to a table mapped with the list of my pojo "Promotion" basically containing the imageUrl, title and similar kind of info.
"ThumbnailFetchListener" and "downloadThumbnail" are interface and method respectively to download the images from server in the separate thread.
"promotion_banner" is the layout I use as the listViewItem.

 private class MyCursorAdapter extends CursorAdapter {

        LayoutInflater inflater;
        int titleColumnIndex;
        int imageUrlColumnIndex;

        public PromotionsGalleryAdapter(Context context, Cursor c,
                boolean autoRequery) {
            super(context, c, autoRequery);
            init(context, c);
        private void init(Context context, Cursor c) {
            inflater = LayoutInflater.from(context);
            titleColumnIndex = c.getColumnIndexOrThrow(Promotions.TITLE);
            imageUrlColumnIndex = c.getColumnIndexOrThrow(Promotions.IMAGE_URL);

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            Logger.log(TAG, "newView called");
            View v = inflater.inflate(R.layout.promotion_banner, null);
            v.setLayoutParams(new Gallery.LayoutParams(
            return v;

        public void bindView(View view, Context context, Cursor cursor) {
            String title = cursor.getString(titleColumnIndex);
            String imageUrl = cursor.getString(imageUrlColumnIndex);
            Bitmap bitmap = null;
            if (TextUtils.isEmpty(imageUrl)) {
            } else {
                bitmap = BitmapCache.loadBitmap(imageUrl);
                if (bitmap == null) {
                            new ThumbnailFetchListener());
                } else {
            ((ImageView) view.findViewById(

        private class ThumbnailFetchListener implements
                ThumbnailDownloadListener {

            public void onComplete(Bitmap bitmap, String url, String filename) {
      , bitmap);

            public void onError(String url) {
                // ignore
            }        }    }

No comments:

Post a Comment