How To Pick Image From Gallery in Android App

Since few days I am working on an Android app and learning all the nitty gritty of its APIs. I will share few How-to stuffs that we frequently require in Android.

To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.

Let us create an example with following requirement:

  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.

So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
	<ImageView
		android:id="@+id/imgView"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:layout_weight="1"></ImageView>
	<Button 
		android:id="@+id/buttonLoadPicture" 
		android:layout_width="wrap_content" 
		android:layout_height="wrap_content" 
		android:layout_weight="0" 
		android:text="Load Picture" 
		android:layout_gravity="center"></Button>
</LinearLayout>

So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.

Thus, on click of button we will trigger following code:

	Intent i = new Intent(
	Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	
	startActivityForResult(i, RESULT_LOAD_IMAGE);

Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.

So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
						
			// String picturePath contains the path of selected Image
		}

Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.

package net.viralpatel.android.imagegalleray;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {
    
	
	private static int RESULT_LOAD_IMAGE = 1;
	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				
				startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			
			ImageView imageView = (ImageView) findViewById(R.id.imgView);
			imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
		
		}
    
    
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
android-gallery-intent-example

User can select an image from Image Gallery
android-gallery-intent-select-image

Once user selects an image, the same will be displayed on our main activity
android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)



51 Comments

  • kevin 25 May, 2012, 13:33

    05-25 23:00:57.952: E/AndroidRuntime(2157): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/23 }} to activity {com.frux.base64/com.frux.base64.galley}: java.lang.NullPointerException

    error dude

    • Viral Patel 25 May, 2012, 16:00

      Hi, In which Line you getting NullPointerException? Also try the demo app that I have attached in your device. Check if you getting same error.

  • kevin 25 May, 2012, 18:14

    at the setting the imageview setImageBitmap,

  • kevin 25 May, 2012, 18:15

    Heres my code hope that you can help me thx in advance!

    protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    		
    		 Intent intent = new Intent();
             intent.setType("image/*");
             intent.setAction(Intent.ACTION_GET_CONTENT);
             startActivityForResult(Intent.createChooser(intent,
                     "Select Picture"), RESULT_LOAD_IMAGE);
    		
    	}
    
    	@Override
    	protected void onActivityResult(final int requestCode, final int resultCode, final Intent imageReturnedIntent) {
    		// TODO Auto-generated method stub
    		  super.onActivityResult(requestCode, resultCode, imageReturnedIntent);   
    		  
    	        switch(requestCode) {  
    	        case RESULT_LOAD_IMAGE:  
    	            if(resultCode == RESULT_OK)  
    	            {  
    	                Uri uri = imageReturnedIntent.getData();  
    	                String[] projection = {MediaStore.Images.Media.DATA};  
    	  
    	                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);  
    	                cursor.moveToFirst();
    	  
    	                int columnIndex = cursor.getColumnIndex(projection[0]);  
    	                String filePath = cursor.getString(columnIndex);  
    	                cursor.close();
    	                Bitmap image = BitmapFactory.decodeFile(filePath);
    	              
    	                ImageView im = (ImageView)findViewById(R.id.imagev);
    	               im.setImageBitmap(image);
    	            }  
    	        }  
    	    }
    
    • Viral Patel 25 May, 2012, 18:56

      Kevin, the way you are triggering Image Gallery is different from what I specified. I am using Intent.ACTION_PICK intent. Can you use the exact code snippet given in above example to trigger the Image Picker.

  • kevin 25 May, 2012, 19:13

    still got an error

    protected void onCreate(Bundle savedInstanceState) {
    		 super.onCreate(savedInstanceState);
    		// TODO Auto-generated method stub
    		 Intent i = new Intent(
                     Intent.ACTION_PICK,
                     android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    
             startActivityForResult(i, RESULT_LOAD_IMAGE);
    	}
    
    	@Override
    	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    		// TODO Auto-generated method stub
    		  super.onActivityResult(requestCode, resultCode, data);   
    		  
    		  if (requestCode == RESULT_LOAD_IMAGE &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) {
    	            Uri selectedImage = data.getData();
    	            String[] filePathColumn = { MediaStore.Images.Media.DATA };
    	 
    	            Cursor cursor = getContentResolver().query(selectedImage,
    	                    filePathColumn, null, null, null);
    	            cursor.moveToFirst();
    	 
    	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    	            String picturePath = cursor.getString(columnIndex);
    	            cursor.close();
    	 
    	            ImageView imageView = (ImageView) findViewById(R.id.imagev);
    	            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    	 
    	        }
    		  
    	    }
    
    • nikhil 31 May, 2012, 11:48

      hey viral can u please send me a code for access images from sqlite db store in sdcard….???

    • Dendrox 2 September, 2012, 5:38

      Hi Viral, Your code is working perfectly, thank you. but i wondered if there is anyway to redirect the image to a different xml layout. I want to access the gallery from main.xml but load it into main2.xml. Thanks

      • Viral Patel 2 September, 2012, 5:49

        Hi Dendrox, I am not sure if I got your requirement clear. I would create an Activity that loads main2.xml and triggers that via Intent from Mainactivity. Also you can pass the image path as extra in intent. Not sure if this would help you.

  • kevin 25 May, 2012, 19:24

    can you pls identify the error.. thx a lot

    • Viral Patel 25 May, 2012, 19:58

      I cannot figure out the issue with the given data :( Could you check if the Demo project is working in your android device? Also try to add few Logcat (Log.d();) statements in your code. You might be able to figure out where exactly you getting null object.

  • Christina 5 June, 2012, 6:00

    hi, this tutorial is working! i have problems in storing the loaded image into sqlite. i browsed through net and found it need to be stored in bitmap or blob? hope u will give a helping hand. Appreciate.

  • ed 29 June, 2012, 1:22

    Been searching for this for a long time.Works perfectly.Thanks a lot.

  • Akanksha 13 July, 2012, 13:36

    so useful Tutorial.it works fine.
    Thanks

  • Sandip 13 July, 2012, 16:27

    Dear Viral,
    Please pos the tutorial which guides how to get started with Android application means from how to add plugins where from we get plugins etc.
    Thanx in advance

  • Vani 18 August, 2012, 11:37

    hi Viral, actually i got error that Resource not found Exception, at line where we are converting columnIndex to string and get path of that gallery image, i can open gallery and when i select image force close is pop up, and got error, can u help why its happen

  • Lakshmi Narayanan 31 August, 2012, 23:38

    Thanks. works cool. But when I do the following xml code, it doesn’t work as expected. Can you please let me know why?

    the method captureImg is not called. To verify, I have a toast to display when the method is called.

    public void chooseImg(View view) {
        	Toast.makeText(this, "Choose Image from Gallery", Toast.LENGTH_SHORT).show();
        	Intent chimg = new Intent(Intent.ACTION_GET_CONTENT);
        	chimg.setType("image/*");
        	startActivityForResult(chimg,CHOOSE_IMAGE_REQUEST_CODE);
    }
    

    Can be some information if you can help me here.

    • Lakshmi Narayanan 31 August, 2012, 23:40

      I use android:onClick on the ImageView and not on the button I want user to click on the Image to choose an image. I have defined it clickable, it is being clicked, but the method is not being called. Can you help me here>?

  • Lakshmi Narayanan 31 August, 2012, 23:38

    xml code

  • jayanga 9 September, 2012, 19:08

    Hey this code is pretty cool
    But the only problem I have is
    “The images I take from camera of my application does not display by this image picker”

    What I’m going to achieve is snap a photo from my application and let user to brows the image folder through your code but it won’t display any of my newly taken images and worst of all it wont display that specific folder I saved those images (/sdcard/DCIM/myFolder)

    but all files display in eclipse file explorer
    Even i remove the device and checked the images or folder is not there

    • Nadeem 23 October, 2012, 16:21

      Hi Jayanga
      I have same problem as is yours. Have you found a solution yet? Please let me know if you have found a solution.
      Many thanks

  • Jayant 20 September, 2012, 8:12

    Thx for the code, it works. however when I convert the image to byte[] using theImage.compress(Bitmap.CompressFormat.JPEG, 10, baos) and store in sqllite db. Later when i read and display I see lot of space – on top and botton of the image. Why is this extra space coming?

  • Tejaswi 4 October, 2012, 14:03

    I imported n ran the sample but on clickijng the load buttin it tells no media Found.. how do i load images into the media?????????can sm 1 teme quicky????????

  • Elzealves 6 October, 2012, 6:01

    I have only one error in:

    public void onClick(View arg0) {

    The method onClick(View) of type new View.OnClickListener(){} must override a superclass method
    How to resolve ?

  • gnanavelu 30 October, 2012, 18:57

    when i am clicking load picture button it showing that (No Media Found)

  • srinivas 7 November, 2012, 17:16

    i want code for android that save the images in sqlite database

  • Fongdue 8 November, 2012, 0:14

    If I want to choose the picture from only one folder. How can I specific the path or uri of folder to get images.

  • Jorge 27 November, 2012, 4:51

    my application failed when my device rotate… the imageview disappears …. Pls someone can help me!!!

    Thanks

  • subbareddy 28 November, 2012, 15:27

    excellent!! it helped me for my way…… than q…

  • jean 1 December, 2012, 16:31

    the same problem than Jorge, the application failed when my device rotate !

    imageView disappears and the load button come back and the activity start again…

    Any advices for fixing that bug ? (I’m testing it on Xperia mini Pro)

    • jean 4 December, 2012, 2:39

      Pb solved:
      U have to write – android:configChanges=”orientation” – in the Manifest of your activity

  • Maria 5 December, 2012, 23:57

    Gallery opens but Image is not being displayed. No error as well. Just the main activity page is displayed.

  • Chandan Bhattad 17 December, 2012, 17:39

    when i pick an image,
    it shows “browser history is empty”

    will you please help me with it?

  • Prateek Sarda 4 January, 2013, 3:02

    Hi Viral, I have added below to my apps manifest file

    this helps me goto Gallery , selet an image and my app name would be shown in Share
    but I am unable to send this selected image to my app. Can you please help me

    Note:I am not opening Gallery from my app but open Gallery and send an image to my open

  • Meenu 8 January, 2013, 0:05

    Hi Viral,
    Your Code Works perfectly fine. :D
    Can you tell me how to assign that image picked to be an xml layout’s-background?
    I tried converting the bitmap to drawable but got null pointer exception or sometimes even memory out of bounds exception. Can you tell me how to do that?

  • Neha 10 January, 2013, 14:51

    Please tell me how can we save the image(from Gallery) on the server.

  • picture taking 18 January, 2013, 2:32

    I will right away seize your rss as I can’t to find your e-mail subscription hyperlink or e-newsletter service. Do you’ve any? Please permit me recognize so that I could subscribe. Thanks.

  • Ruchi Agarwal 8 February, 2013, 21:45

    Viral, good tutorial. Any idea if there is a way to understand the camera capacity in Android devices?

  • Mansi 11 February, 2013, 12:02

    Perfect piece of code. Thanks.

  • welly 19 February, 2013, 18:04

    i wan’t to show specific folder, why cannot be show?
    Please someone can help me!!! Thankssss…

    
    Intent intent = new Intent(Intent.ACTION_PICK)
    			    intent.setDataAndType( Uri.parse("file:/"+ Environment.getExternalStorageDirectory()+"/DCIM/MySpecificFolder/"),"image/*");
    				startActivityForResult(intent, RESULT_LOAD_IMAGE);
    
    
  • Qadir Hussain 26 February, 2013, 17:58

    I follow this tutorial. How can i get image size. I want to select the image of 300 X 300. where should i put this condition so that user should be restricted to select only the images having 300X300 dimensions? reply plz.

    Regards
    Qadir Hussain

  • Ravi Kumar 1 March, 2013, 22:15

    Thank u so much .this tutorial is very helpful.
    But ,Can you plz tell me ,that how i can create gallery programitically and how i can store all images in that gallery.

  • Paolo 2 March, 2013, 19:38

    Thank you so much! Great tutorial! Ciao :)

  • Gabriel 7 March, 2013, 7:08

    As I can make it work in a file that is not principal activity?

  • Dnyaneshwar 19 March, 2013, 12:53

    Thank you for such good tutorial.That tutorial is helpfull for me ………

  • Eshrath 26 March, 2013, 11:29

    hai… how to import image in gallary

  • mita 30 March, 2013, 16:53

    Very Useful Post…

    Can u have example for capture photo or select from existing or use avatar

    Actually i am developing user profile apps so i want it…

  • Rajanikanth 30 March, 2013, 17:44

    hi… Thanks for article. Really helpful :)

  • Adrian 3 April, 2013, 0:21

    Hi,

    Thanks for posting the tutorial. It helped me a lot in my current project. However, I believe I have spotted an error. My native gallery collects images from the camera, downloaded applications and other applications that allow one to take images. If I tried to display an image from the camera gallery, it works perfectly. If I try to use an image from other application (eg Twitter) I get NullPointerExpception error (bummer). I logged out the location of the file(s)

    working image –

     content://media/external/images/media/11028 

    not working image –

     content://com.google.android.gallery3d.provider/picasa/item/5719782242839264946 

    Any suggestions? Can we amend the code above so it could be used with any image regardless of its location?

    Thank you in advance

    • Alexia Winter 9 April, 2013, 22:56

      The same problem. Need to find a universal solution for any path of images.

  • Iyer 16 May, 2013, 20:18

    Apparantely, this code works if you try to pick the photos from camera. If the user has a picasa account and if you try to pick the photo from picasa albums (which also shows up in gallery), it throws a null pointer exception in im.setImageBitmap(image); because your filepath is null.the path of the picasa album is different from the path of camera (local) pictures. So, for people who are searching for it in future,here is the link which might be useful to you.

    http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]