Monday, September 28, 2009

Displaying images from SD card in Android

Below you will find a Android example of how to access and display images that are stored on your SD card.

I wrote part 2 for this article, where images are loaded in the background using an asynchronous task. It is an improvement over this article, but I strongly suggest trying this one first to fully appreciate the differences between the two approaches.

The main idea is to make use of the MediaStore class, which is a Media provider that contains data for all available media on both internal and external storage devices (such as an SD card). An adapter is used as a bridge between the data and the view.

The activity is shown below:

package blog.android.sdcard;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Displays images from an SD card.
 */
public class SDCardImagesActivity extends Activity {

    /**
     * Cursor used to access the results from querying for images on the SD card.
     */
    private Cursor cursor;
    /*
     * Column index for the Thumbnails Image IDs.
     */
    private int columnIndex;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sdcard);

        // Set up an array of the Thumbnail Image ID column we want
        String[] projection = {MediaStore.Images.Thumbnails._ID};
        // Create the cursor pointing to the SDCard
        cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection, // Which columns to return
                null,       // Return all rows
                null,
                MediaStore.Images.Thumbnails.IMAGE_ID);
        // Get the column index of the Thumbnails Image ID
        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

        GridView sdcardImages = (GridView) findViewById(R.id.sdcard);
        sdcardImages.setAdapter(new ImageAdapter(this));

        // Set up a click listener
        sdcardImages.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                // Get the data location of the image
                String[] projection = {MediaStore.Images.Media.DATA};
                cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        projection, // Which columns to return
                        null,       // Return all rows
                        null,
                        null);
                columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToPosition(position);
                // Get image filename
                String imagePath = cursor.getString(columnIndex);
                // Use this path to do further processing, i.e. full screen display
            }
        });
    }

    /**
     * Adapter for our image files.
     */
    private class ImageAdapter extends BaseAdapter {

        private Context context;

        public ImageAdapter(Context localContext) {
            context = localContext;
        }

        public int getCount() {
            return cursor.getCount();
        }
        public Object getItem(int position) {
            return position;
        }
        public long getItemId(int position) {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView picturesView;
            if (convertView == null) {
                picturesView = new ImageView(context);
                // Move cursor to current position
                cursor.moveToPosition(position);
                // Get the current value for the requested column
                int imageID = cursor.getInt(columnIndex);
                // Set the content of the image based on the provided URI
                picturesView.setImageURI(Uri.withAppendedPath(
                        MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
                picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                picturesView.setPadding(8, 8, 8, 8);
                picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
            }
            else {
                picturesView = (ImageView)convertView;
            }
            return picturesView;
        }
    }
}
The layout of the main activity is shown below:

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/sdcard"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

In order for this to work, you need to emulate an SD card.

Enjoy!

UPDATE (October 19, 2009): In order to be bale to view thumbnails images from the SD Card, Android needs to create them first, hence you should start the Gallery application that comes preinstalled, and open the sdcard folder which will automatically create thumbnails for the images stored on your sdcard. This is a current shortcoming of the SDK that will be fixed in future releases (http://groups.google.com/group/android-developers/browse_thread/thread/3f01b284e2537312/fa9487d19db4907e).

UPDATE (October 07, 2009): For some reason, if you use
MediaStore.Images.Thumbnails.IMAGE_ID
like in the previous version of the above code, the images are not always displayed on the screen. Changing to
MediaStore.Images.Thumbnails._ID
seems to solve the problem. I will look more into why and get back to you.
Furthermore, some images have the wrong path attached to them.  I changed the creation of the cursor object from
cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null,       // Return all rows
null,
null);
to
cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null,       // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);

446 comments:

«Oldest   ‹Older   401 – 446 of 446
appliance repair Olathe Olathe said...

Its Very good feeling to read your post

meettv said...

Welcome To Meettv, We Brought To You All Indian Desi Tv Dramas, Watch Your Favorite Desi Tv Drams And Shows, Colors Tv Serials, Zee Tv Serials, Star Plus Serials, Sony Tv, Watch Today Desi Serials Episode, All Indian Tv Drasam and Show Latest Episode Live Stream, Watch Online Your Farovite Tv Show

Today Episode

BA Time Table said...

ba 3rd year ka time table

Bigg Boss 16 Today Episode said...

Watch Bigg Boss 16 Popular television actor Karan Kundrra is all set to be a contestant on
Salman Khan hosted Bigg Boss 16 Online Live Episodes. Known for his roles on television...

Husnain said...

DramaCool is the best platform offering you a good selection of dramas and kshow. Our consistently high-quality videos will not let you down. Both the sound quality and the subtitles of dramas on this site are excellent,
and they have been synched with the videos incredibly well.

Dramacool
KissAsian Dramas

Creative Studio said...

Thanks for providing such a great information.

mahnoor khan said...

Valuable website are you looking for graphic designer visit my website
ideahits

Jobi Johnson said...

Nice post. Thank you to provide us this useful information. Heartstopper Nick Nelson Jacket

Anas said...

Perfect Tutor has the largest network of trained and screened home tutors across India.
We provide a simple and sorted way for students and parents looking for home tutors, and online tutors near their location.
We also provide teaching and tutoring jobs to tutors and teachers looking for part-time teaching jobs.

appliance repair Green Bay said...

this post showed your intention of article, your quality of writting.

Divorce attorneys said...

The way you have explained your article post, thats amazing.

Confidence for children with nlp4kids said...

Enjoyed to read the article of this page, good work

Mental health help for employees said...

This is one of best article i found online

Hypnotherapy North London said...

The place I get that kind of information written in such an ideal means

FBacklink said...

if any user want to add FREE Backlink of their website or submit seo link building free with high TF/CF site you can check this site - https://fbacklink.com

Raushni Gupta said...
This comment has been removed by the author.
Raushni Gupta said...

I am very enjoyed for this blog. Its an informative topic.Amazing website, Must Visit
India Helicopter Tourism

Anonymous said...

We at Graphics Design hub take pride in giving our clients the most exhaustive scope of android application arrangements. In this way, in the occasion you are searching for a App development company reach us immediately.

huzaifa siddique said...

Thanks for giving us such a great information I am also operating clothing store which includes bridal dresses, top trending clothing.
Pakistani bridal wear usa

huzaifa siddique said...

Thanks for sharing excellent information. Your site is very cool. I am impressed by the details that you have on this site.I am also operating clothing store which includes bridal dresses, top trending clothing.
Pakistani bridal wear usa

Anas said...

The perfect tutor provides the best home tutor in Pune. All the teachers are well-experienced and qualified with good teaching skills.

Anas said...

We are the best home tutor in Hyderabad with good experienced and qualified tuition teachers. The perfect tutor serves the home tuition service in Hyderabad for the past 5 years.

Anas said...

The perfect tutor provides the best service of home tutors in Bangalore. All the tutors have good experience and teach according to the career of the candidate. Good guidance and support.

Anas said...

In this is easy now to engage your child with best home tutor in Chennai. Very easy to enroll and good opportunity for students to take best coaching from teachers.

Anas said...

Perfect tutor is the best home tutor in greater noida with the good experianced tutor and give quality teaching service.

Unknown said...

We give the best home tutor service in Gurgaon. All the students have the opportunity to engage with the best tuition teacher and also take free demo classes for any subject anywhere in Delhi.
Enroll Now and grab it.

Oven repair Kansas said...

You are a GREAT blogger, i must say Thanks for post blog for us all the times.

X16Thori II said...

I think this is a standout amongst the most huge data for me. Furthermore, i'm happy perusing your article. Be that as it may, ought to comment on some broad things, The site style is flawless, the articles is truly incredible : D. Great job, salud
flow control

Perfect Tutor said...

Perfect Tutor makes it easier to find gifted home tutors who pay close attention to every scholarly subject. Perfect Tutor allows parents and children to research the best teachers, including accreditations, rates, client surveys, and academic methodologies. We created a framework tailored to your needs to assist you in locating the top teachers in Bangalore for various trains and courses. You may get the greatest at-home educators or online guides in Bangalore by advertising your educational requirements for free on our website.
Please visit :-https://www.perfecttutor.in/

Anas said...
This comment has been removed by the author.
Talk To Iconic said...

I really appreciate your post and you explain each and every point very well.Thanks for sharing nice article. Talk To Iconic News

Meet Watch Online said...

Meet serial is best drama serial online from Zee tv Indian drama

Webwire Media said...

Thanks for sharing this informative blog post. I'll be looking forward to reading more from you. You can promote your content using digital marketing services.

Waqas Raza said...

Thanks for sharing the information. We offer the best digital marketing services in Pakistan. Contact us for business promotion.
For bookkeeping and accounting services in Dubai visit Kabanico.ae

concrete leveling Hartford said...

I struggle to find blog post like yours, i m going to folow your post.

Gecko said...

Very Nice

redneckgamer07 said...

You have made an extraordinary showing on this article. It's exceptionally comprehensible and very savvy. You have even figured out how to make it justifiable and simple to peruse. You have some genuine composition ability. Much obliged to you.


home staging orleans

Bulk Email Service Provide said...

Some truly wonderful content on this web site , appreciate it for contribution.
Bulk Email Sending Service Provider
Mass Mail Service Provider

Gecko said...

app to watch free movie
watch short movies online free
watch short films online free
watch short films
short movies to watch
short movies online
Short film app
Short Film App
app to watch free movie

Single Property Websites For Realtors said...

Fantastic blog!!! Thanks for sharing with us, Waiting for your upcoming data
Single Property Websites
Single Property Sites

estate planning attorney said...

I really learned a lot from you.

Cyber security services said...

I had never imagined that you can have such a great sense of humor.

refrigerator repairs Milwaukee said...

i think you should keep it up, amazing. thank you

ISO Mobile App Development said...

As an app development company, incorporating this functionality into your Android applications can greatly enhance the user experience and make your app stand out from the competition. By enabling users to easily browse and display images from their SD cards within your app, you are providing them with a convenient and seamless way to access their visual content.

My Invite Link said...

Just got a new high-capacity memory card for my camera, and I'm ready to capture some epic shots for my 'Photography Passion' private story names. More storage, more memories!

James Gambil said...

"Logovent: Your One-Stop Shop for Low-Cost Website Creation Services. At Logovent, we recognize the value of having a polished and interesting web presence without going over budget.

«Oldest ‹Older   401 – 446 of 446   Newer› Newest»