Android PhotoPicker using Intents and Gallery

Sometimes you need to select a photo. To make it convenient for the user, you should search all the images on the device, generate thumbnails, create a touch&go interface, and a lot more details, that take some considerable time to implement. Luckily we can use the default Android Gallery instead, and invoke it from withing our application:

The code to achieve this is very easy and straightforward. For the demo app, I’ve created a LinearLayout that holds a TextView (for displaying messages) a Button (to select the image) and an ImageView (to display the image selected). Pressing the button, invokes the Gallery intent, for ACTION_PICK / image picking.

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, idIntentID);

We start this intent using startActivityForResult, passing the idIntentID variable. We also need to make sure the main class overrides onActivityResult. By doing so, we will receive a notification when the user has chosen a picture or has canceled the Photo picker:

	  protected void onActivityResult(int requestCode, int resultcode, Intent intent)
		  super.onActivityResult(requestCode, resultcode, intent);
		  if (requestCode == idIntentID) {
			  if (intent != null) {
				  Log.d(LOG_TAG, "idButSelPic Photopicker: " + intent.getDataString());
				  Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
				  cursor.moveToFirst();  //if not doing this, 01-22 19:17:04.564: ERROR/AndroidRuntime(26264): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
				  int idx = cursor.getColumnIndex(ImageColumns.DATA);
				  String fileSrc = cursor.getString(idx); 
				  Log.d(LOG_TAG, "Picture:" + fileSrc);
				  m_Tv.setText("Image selected:"+fileSrc);
				  Bitmap bitmapPreview = BitmapFactory.decodeFile(fileSrc); //load preview image
				  BitmapDrawable bmpDrawable = new BitmapDrawable(bitmapPreview);
			  else {
				  Log.d(LOG_TAG, "idButSelPic Photopicker canceled");
				  m_Tv.setText("Image selection canceled!");

It’s easy, but very useful for many applications. Here is the sample project code:

This article has 2 Comments

  1. in the above example it displays all the images present in the phone instead is tehre any way to display images from particular directory????

  2. Thanks a lot.It really helped me,but I m getting a problem with this.
    When i add new image in sdcard,it doesnt show that in the photopicker.

Leave a Reply