Select an Image from gallery in ANDROID and show it in an ImageView.

Hi all
In this tutorial I will show you how to get an image from your phone gallery and show it in an imageview.
Here we use intents to open up the image gallery and get the image URI.
Here I am setting the image type as “image” to get only the images.
And on onActivityResult if the result is OK, then get the data using getData() function and converting the imageURI to the stringPath.
Then show the image in the imageview using setImageURI.

package pack.GetImage;

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

public class GetImageActivity extends Activity {

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);

	    img = (ImageView)findViewById(R.id.ImageView01);

	    ((Button) findViewById(R.id.Button01))
	            .setOnClickListener(new OnClickListener() {
	                public void onClick(View arg0) {
	                    Intent intent = new Intent();
	                    intent.setType("image/*");
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	                }
	            });
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            System.out.println("Image Path : " + selectedImagePath);
	            img.setImageURI(selectedImageUri);
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
}

Here is the main.xml file


<?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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Browse gallery"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/ImageView01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</ImageView>
</LinearLayout>

Please leave your valuable comments if you found this post useful.

34 thoughts on “Select an Image from gallery in ANDROID and show it in an ImageView.

  1. idoudi

    thank you very much for this tuto…:)))
    but I have a problem with the size of the imageView. It does not take the space I have reserved in xml file.
    can u help me please…

    Reply
    1. James

      Can’ t really understand the question. I think the problem may be because your image resolution is too small to fit in the provided xml size.

      Reply
  2. remy215

    You’re the man! I’ve spent hours trying to figure out why I could not open file based on value returned by data.getPath(). This is in fact because it is not the real file path and I was missing all of the projection & cursor stuff.
    Thanks a lot.
    Remy

    Reply
  3. Pingback: android: cannot load external pictures [solved] « Willing wheels

  4. dabious

    Code works perfect, however after selecting a photo if i click my add photo button again and select a different photo the app force closes . Any way to make this work?

    Reply
  5. dabious

    Code works great but I am running into this issue.. external allocation too large for this process. Any tutorials on how to implement a down sampling to the images that works with your code above?

    Reply
  6. vineet

    When your code is run then give same message un fortunately camera has stopped.
    please help me
    Please reply as soon as possible

    Reply
    1. James

      Hey vineet, please check the logcat and paste here the reason for this problem. then only I can help, because this is a perfectly working code.

      Reply
  7. Christina

    Hi, this works perfectly. But, how if i want to save it into database? can you show me the codes? i’ve spent days on this problems.
    Thanks in advance. Appreciate.

    Reply
    1. James

      Don’t save the image to the database, but save it to the SDCARD or the application sandbox and save the corresponding path in the database.

      Reply
  8. Pitr

    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”
    Can you help me here?
    Thanx in advance

    Reply
  9. falah

    hi.i have got error in this two line
    1.import android.provider.MediaStore;
    2. private static final int SELECT_PICTURE = 1;
    please help me…

    Reply
    1. James

      You will get the path of the image just pass it with putExtra to the next activity and show it in the same way. that’s all.

      Reply
  10. jalil

    Hi,
    From API 11
    the “managedQuery()” method is depricated
    so does any one have any isea as how the same program can be done for API 11 and above

    Eclipse adiced to use CursorLoader
    but i dont know how to use it

    Reply
  11. Aisha

    thanks for nice info. :)
    Ngg.. I’m a student and start learn android,
    I tried to use this code to take two different picture from gallery and display it into two different imageview.
    But it can’t work. I just success to display first image, but not for the second.
    Do you know why is it?

    Reply
    1. James

      Are you setting in the imageview correctly. check once more. it should work with any image.please check your pic request id also.

      Reply
  12. sri

    Hi, I have used this code to upload a picture in the header of list view in the Side Menu Navigation. It works fine but, when I close the application, the image disappears. Is there any solution for that?

    Reply
  13. gayathri

    Hey there, i am having the same prob, which say the process has stopped. Cn i check if the ” Cursor cursor = managedQuery(uri, projection, null, null, null);” needs to be deprecated?

    Reply
  14. faffou

    Thank you for this tuto, , it works successfully, but i need the same work for an xml file. I mean i want to open and read an xml file. the problem is that i can’t see my file in the galery. Have you any suggestion ??

    Reply
    1. James

      Gallery is for images and videos only, not for other types of files.
      Install a file explorer app like ES file explorer and there going to right path you can see the XML file.

      I think your question is “you want to select an xml file by opening a file explorer” Isn’t it?
      Then you have to make a file browser or Check in Google for Libraries like that.
      I am sure You will find more than one.

      Thanks

      Reply
      1. faffou

        The problem is that when i click to the button to browse my phone contents, i can see only: galerie, contacts, photos and the MP3 player, so how can i access to the other folders.
        Thinks

        Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>