Android has a standard intent action called ACTION_PICK that allows the user to choose from a set. This type of intent is often used in conjunction with a URI, but it need not be. This kind of intent can also be used to create a set of all data of a given MIME type on the handset and allow the user to choose an item from the set.
For example, you can create an intent to use within the onLongClick() method to display all images to the user as follows:
Intent pickPhoto = new Intent(Intent.ACTION_PICK); pickPhoto.setType("image/*");
When you run the application and long-click the avatar ImageButton control, a gallery of images available on the device is displayed (see Figure 13.5).
Choosing an image from the gallery on the Android emulator.
The ACTION_PICK Intent action causes a gallery of all images stored on the handset to launch, allows the user to choose one image, and returns a URI address to the image's location. Therefore, within a specific case statement of the onActivityResult() method for the request code TAKE_AVATAR_GALLERY_REQUEST, you can retrieve the URI by inspecting the Intent parameter called data, as follows: Uri photoUri = data.getData();
Then, to convert the Uri to a valid Bitmap object, you can use the following method:
Bitmap galleryPic = Media.getBitmap(getContentResolver(), photoUri); You can then pass the bitmap into your helper method called saveAvatar().
Was this article helpful?