Displaying images from SD card in Android

Hello friends!

In one of my earlier tutorials, we had learnt how to display images using the GridView layout in Android. Sometimes, developers need to fetch images from a SD card storage. In order to read or write files on the external storage, an Android application must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permission.

Through this post, we will learn how to display images from a SD card in Android. In addition, we will display these images using a GridView.

Pre-requisites: Eclipse IDE, Android SDK

In any of existing Android projects create a new Activity class called DisplayImageActivity with package name com.example

Add the following code to your Activity class!

DisplayImageActivity.java

package com.example;

import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.GridView;
import android.widget.Toast;

public class DisplayImageActivity extends Activity {

	private ImageAdapter imageAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_grid);

		GridView gridview = (GridView) findViewById(R.id.gridview);
		imageAdapter = new ImageAdapter(this);
		gridview.setAdapter(imageAdapter);

		String ExternalStorageDirectoryPath = Environment
				.getExternalStorageDirectory()
				.getAbsolutePath();

		String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";

		Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
		File targetDirector = new File(targetPath);

		File[] files = targetDirector.listFiles();
		for (File file : files){
			imageAdapter.add(file.getAbsolutePath());
		} 
	}
}

ImageAdapter.java

package com.example;

import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {

	private Context context;
	ArrayList<String> imageList = new ArrayList<String>();

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

	void add(String path){
		imageList.add(path); 
	}

	@Override
	public int getCount() {
		return imageList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView;
		if (convertView == null) {  
			imageView = new ImageView(context);
			imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(8, 8, 8, 8);
		} else {
			imageView = (ImageView) convertView;
		}

		Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 220, 220);
		imageView.setImageBitmap(bm);
		return imageView;
	}

	public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

		Bitmap bm = null;
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

		options.inJustDecodeBounds = false;
		bm = BitmapFactory.decodeFile(path, options); 

		return bm;   
	}

	public int calculateInSampleSize(

		BitmapFactory.Options options, int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float)height / (float)reqHeight);    
			} else {
				inSampleSize = Math.round((float)width / (float)reqWidth);    
			}   
		}

		return inSampleSize;    
	}

}

activity_grid.xml

<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">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>

</LinearLayout>

AndroidManifest.xml

Add the below permission in the manifest file!

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

output

Reference: Storage options in Android

Karan Balkar About Karan Balkar
self proclaimed extraterrestrial fandroid, computer engineer, amateur gamer and die hard punk rock fan!

19 thoughts on “Displaying images from SD card in Android

  1. i have ran the code but all that comes on the screen is a blank white page.. i have the images in my external DCIM/Camera folders. kindly explain…

  2. hello i tried this code its working in Kitkat version but not not working in Lollipop, Can you please provide solution for Lollipop ?

  3. thank you for your codes.
    but i would like to know if its possible to read only jpeg file from my sd card?pls send me this codes.thank you again.

  4. hi
    this is perfect code but i want when click on each pic show the pic in full size
    i have a “fullImage” activity but i don’t know how get position with this imageAdapter
    can you help me??

  5. I am getting file’s absolute path in logcat but when I do this “gvAdapter.add(file.getAbsolutePath());” my app crashes, I am getting this error:
    java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.akramamirza.photobabble.GridViewAdapter.add(java.lang.String)’ on a null object reference
    at com.akramamirza.photobabble.SendFragment.onCreateView(SendFragment.java:100)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:5938)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

  6. Getting error on load class..

    File[] files = targetDirector.listFiles();
    for (File file : files){
    imageAdapter.add(file.getAbsolutePath());
    }

Leave a Reply

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