Friday, August 9, 2013

Android Gallery Intent Example

Android gallery intent is a simple way for users to select images for use in your application. It also makes the  mobile app developer's life easier by not having to implement a graphic user interface for users to use to import an image. There are two different intents that you can implement for users to select an image and import it into your application. You can view my gallery intent example source code in my android-api-example Github project.


Gallery Intent Using Default Gallery Application

If you want to start a gallery application that uses the device's default gallery app, you just need to call the Intent with MediaStore.Image.Media.EXTERNAL_CONTENT_URI and do Activity.startActivityForResult() instead of Activity.startActivity() on that intent. This way, you can retrieve the image path that the user has selected. Then in your overridden Activity.startActivityForResult() it just a matter of retrieving the path where the image is located. Now the tricky part is getting the file path. Tricky because the image file path isn't simply just store in the Intent data variable. Basically, the information returned will in a form of database query, thus a bit of code required to get that file path. Below is the code that I use to get the image file path (for now ignore the else if block of the code). And that is it, with that image file path decode into Bitmap and use it however you like!

Gallery Intent Using with Ability to Choose Gallery Application

Just automatically opening up the default gallery application does not give much choice for your users, hence I will describe how you can give users more flexibility when selecting images on the device. Simply when you create the intent, first specify what type of file you would like to import using MIME type and telling that you want to get some form of content using the constant Intent.ACTION_GET_CONTENT and then finally invoke Activity.startActivityForResult().
Similar to using gallery intent on default gallery app, in Activity.startActivityForResult() get the image file path using the provide code above. I have also mentioned above to ignore the else if block of code. This is where that block of code becomes useful. In the case where the user uses other apps (not the default gallery app), it will return the file path in the Intent data variable, thus it can get easily retrieved.
You can view my Android Camera Intent example HERE.
Relevant files are:
src/com/choiboi/apiexamples/gallery/GalleryMainActivity.java
res/layout/activity_gallery_main.xml

Enjoy!!