Loading Images in Android (Part III: Pick images from Gallery)

In Part III we will look on how to let the user pick an image from the Android Gallery and display it in your application.
When clicking on the Pick Image button, the Android media gallery will open allowing you to browse for a photo, select it, and finally display it in the application.

Below is the XML layout of the above Activity. It consists of a Button that will trigger the pick action, and an ImageView that will display the selected photo.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/pick_image_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Image" />

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

And this is the Activity that manages all the job on picking an displaying the picture.
public class ImagePickerActivity extends ActionBarActivity {

   private static final int PICK_IMAGE = 100;
   private ImageView imageView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_image_picker);

      imageView = (ImageView) findViewById(R.id.image_view);

      Button pickImageButton = (Button) findViewById(R.id.pick_button);
      pickImageButton.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
            openGallery();
         }
      });
   }

   private void openGallery() {
      Intent gallery = 
         new Intent(Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
      startActivityForResult(gallery, PICK_IMAGE);
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
         Uri imageUri = data.getData();
         imageView.setImageURI(imageUri);
      }
   }
}

How Picking an Image from Gallery Works

The Gallery which displays the user's photos is a separate application over which we don't have control, in the sense that there isn't an API that will allow us to manipulate the Gallery from inside our app.
However, Android has a mechanism that allows us to get a result from another Activity, even if that activity is not ours. This is accomplished by calling startActivityForResult() (instead of startActivity()), and overriding onActivityResult() to retrieve the result from the previous started Activity.

startActivityForResult() takes two parameters, the Intent to start and a request code.
private static final int PICK_IMAGE = 100;
// ...
private void openGallery() {
   Intent gallery = 
      new Intent(Intent.ACTION_PICK, 
      android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
   startActivityForResult(gallery, PICK_IMAGE);
}

The intent to start can be explicit (when the name of the activity to be started is known, usually used when calling one of your activities) or implicit (when other activities, usually that are not part of your application, can perform the action). In the above example an implicit intent is used.

The "request code" (PICK_IMAGE) is an integer number that identifies your request (doesn't have to be "100", you can use any integer number). When receiving the result in the onActivityResult() callback, the same request code is provided so that your app can properly identify the result and determine how to handle it.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   
   // If the result is OK (user finished the action)
   // and the request code is our code,
   // then this is our request and we can process the result
   if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
       // process the result
   }
}

And the result returns the Uri of the selected picture (an Uri can be regarded as the "address" or an identifier of the picture), which is passed to the ImageView to load and display.
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);

7 comentarii:

  1. Your tutorial is awesome.. Keep it up. Kindly Create tutorial on selecting image and adding to sqlite database (Recyclerview, listview etc..)

    RăspundețiȘtergere
    Răspunsuri
    1. it's a most stupid idea, but i has been seen in many times it. Image must saving in memory and linked in sqlite by file path

      Ștergere
  2. good post dr.. u solved my requirement ..
    thanks

    RăspundețiȘtergere
  3. awesome post very helpful thanks man for your tutorial

    RăspundețiȘtergere
  4. Great explanations. Thanks for the post!

    RăspundețiȘtergere