Sunday, November 18, 2012

Tech post alert!

While working on my next application, I have stumbled upon the problem of how to read user pictures and display them in ImageView. There are a bazillion posts and tutorials on the web, but they all are either needlessly overcomplicated, or aren't doing what is needed - for example, most of them are using ACTION_GET_CONTENT to pick and display a single image from the gallery, instead of reading them all in sequence and displaying as they come.

So, for my fellow Android developers, here is the absolute easiest and quickest way to read and display user gallery on Android phones using nothing but cursors.

1. Get the data into cursor:
Cursor cc = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,null);
2. Get the contents of _DATA (!) field from it (not ID as some posts suggest), which contains the actual physical path to the file.
int i_data = cc.getColumnIndex("_data"); String s_data = cc.getString(i_data);
3. Decode the bitmap and assign to ImageView
Bitmap b = BitmapFactory.decodeFile(s_data); im.setImageBitmap(b);
That's it! I can't believe it has taken me so much time to figure this out, and I hope this helps someone to avoid wasting as much time as I just have.

No comments:

Post a Comment