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>
Code language: HTML, XML (xml)

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);
Code language: Java (java)

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 }
Code language: Java (java)

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)); } } }
Code language: Java (java)

Screen shots of Android app

First screen: Lets user to trigger Image Gallery

User can select an image from Image Gallery

Once user selects an image, the same will be displayed on our main activity

Download Source Code

ImageGalleryDemo.zip (46 KB)

View Comments

  • 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

    • 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.

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

    [code language="java"]
    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);
    }
    }
    }
    [/code]

    • 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.

  • still got an error

    [code language="java"]
    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));

    }

    }
    [/code]

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

    • 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

      • 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.

    • 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.

  • 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.

  • 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

  • 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

Share
Published by
Viral Patel
Tags: android android-intent image-gallery java code

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago