Android Display Images from SD Card Tutorial

In this tutorial, you will learn how to display images on a GridView that are stored on your device SD Card. We will create a GridView and show images that are stored on an SD Card folder and on the GridView item click will display the selected image on a new activity. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project SDImageTutorial.

Application Name : SDImageTutorial

Project Name : SDImageTutorial

Package Name : com.androidbegin.sdimagetutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.sdimagetutorial;

import java.io.File;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

	// Declare variables
	private String[] FilePathStrings;
	private String[] FileNameStrings;
	private File[] listFile;
	GridView grid;
	LazyAdapter adapter;
	File file;

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

		// Check for SD Card
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
					.show();
		} else {
			// Locate the image folder in your SD Card
			file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "SDImageTutorial");
			// Create a new folder if no folder named SDImageTutorial exist
			file.mkdirs();
		}

		if (file.isDirectory()) {
			listFile = file.listFiles();
			// Create a String array for FilePathStrings
			FilePathStrings = new String[listFile.length];
			// Create a String array for FileNameStrings
			FileNameStrings = new String[listFile.length];

			for (int i = 0; i < listFile.length; i++) {
				// Get the path of the image file
				FilePathStrings[i] = listFile[i].getAbsolutePath();
				// Get the name image file
				FileNameStrings[i] = listFile[i].getName();
			}
		}

		// Locate the GridView in gridview_main.xml
		grid = (GridView) findViewById(R.id.gridview);
		// Pass String arrays to LazyAdapter Class
		adapter = new LazyAdapter(this, FilePathStrings, FileNameStrings);
		// Set the LazyAdapter to the GridView
		grid.setAdapter(adapter);

		// Capture gridview item click
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent i = new Intent(MainActivity.this, ViewImage.class);
				// Pass String arrays FilePathStrings
				i.putExtra("filepath", FilePathStrings);
				// Pass String arrays FileNameStrings
				i.putExtra("filename", FileNameStrings);
				// Pass click position
				i.putExtra("position", position);
				startActivity(i);
			}

		});
	}

}

In this activity, we will check for the SD Card existence and if exist will create a new folder on your SD Card. The image file paths and names from the SD Card are stored in an array and passed to the GridViewAdapter to set it into the GridView. On GridView item click will show the selected image in a new activity.

Next, create an XML graphical layout for your MainActivity. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file gridview_main.xml and paste the following code.

gridview_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dip" >

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

</RelativeLayout>

Output:

SD Image Tutorial Main XML

Next, create a GridView adapter class. Go to File > New > Class and name it GridViewAdapter.java. Select your package named com.androidbegin.sdimagetutorial and click Finish.

Open your GridViewAdapter.java and paste the following code.

GridViewAdapter.java

package com.androidbegin.sdimagetutorial;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridViewAdapter extends BaseAdapter {

	// Declare variables
	private Activity activity;
	private String[] filepath;
	private String[] filename;

	private static LayoutInflater inflater = null;

	public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
		activity = a;
		filepath = fpath;
		filename = fname;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}

	public int getCount() {
		return filepath.length;

	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View vi = convertView;
		if (convertView == null)
			vi = inflater.inflate(R.layout.gridview_item, null);
		// Locate the TextView in gridview_item.xml
		TextView text = (TextView) vi.findViewById(R.id.text);
		// Locate the ImageView in gridview_item.xml
		ImageView image = (ImageView) vi.findViewById(R.id.image);

		// Set file name to the TextView followed by the position
		text.setText(filename[position]);

		// Decode the filepath with BitmapFactory followed by the position
		Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

		// Set the decoded bitmap into ImageView
		image.setImageBitmap(bmp);
		return vi;
	}
}

This is an adapter class for the GridView that retrieves String arrays from the MainActivity and sets the image file paths and names into the GridView followed by the positions.

Next, create an XML graphical layout for the GridView items. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file gridview_item.xml and paste the following code.

gridview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dip" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image" />

</RelativeLayout>

Next, create a new activity in a new class called ViewImage. Go to File > New > Class and name it ViewImage.java. Select your package named com.androidbegin.sdimagetutorial and click Finish.

Open your ViewImage.java and paste the following code.

ViewImage.java

package com.androidbegin.sdimagetutorial;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewImage extends Activity {
	// Declare Variable
	TextView text;
	ImageView imageview;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from view_image.xml
		setContentView(R.layout.view_image);

		// Retrieve data from MainActivity on GridView item click
		Intent i = getIntent();

		// Get the position
		int position = i.getExtras().getInt("position");

		// Get String arrays FilePathStrings
		String[] filepath = i.getStringArrayExtra("filepath");

		// Get String arrays FileNameStrings
		String[] filename = i.getStringArrayExtra("filename");

		// Locate the TextView in view_image.xml
		text = (TextView) findViewById(R.id.imagetext);

		// Load the text into the TextView followed by the position
		text.setText(filename[position]);

		// Locate the ImageView in view_image.xml
		imageview = (ImageView) findViewById(R.id.full_image_view);

		// Decode the filepath with BitmapFactory followed by the position
		Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

		// Set the decoded bitmap into ImageView
		imageview.setImageBitmap(bmp);

	}
}

This activity retrieves the positions and string arrays from the GridView item click in MainActivity.java using intent and sets the image file paths and names into a ImageView and TextView.

Next, create an XML graphical layout for your ViewImage. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file view_image.xml 

Open your view_image.xml and paste the following code.

view_image.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/full_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/imagetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="20dip" />

</RelativeLayout>

Next, change the application name. Open your strings.xml in your res > values folder and paste the following code.

strings.xml

<resources>

    <string name="app_name">SDImage Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">SDImage Tutorial</string>

</resources>

In your AndroidManifest.xml, we need to declare a permission to allow the application to write an external storage. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.sdimagetutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:uiOptions="splitActionBarWhenNarrow" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ViewImage" >
        </activity>
    </application>

</manifest>

Run the application and you should see a folder named SDImageTutorial on your SD Card. For this tutorial, we have prepared some sample images. Insert your downloaded sample images into your SDImageTutorial Folder as shown on the screenshot below.

Sample Images

[wpfilebase tag=file id=31 tpl=download-button /]

Upload Images to SDImageTutorial Folder

Output:

SD Image Tutorial ScreenShots

Source Code 

[purchase_link id=”7898″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

hello this is very slow then tell me how to create fast

varun sharma

Android Display Images from SD Card Tutorial

I have one error though ,the LazyAdapter on the MainActivity . T.T Please help me ASAP . Im using Android Studio 2.2.2

Jayson Aquino

Android Display Images from SD Card Tutorial

How to select multiple images at a time and perform operation like delete and share....in same program......plz kindly help me

Aashish Pardeshi

Android Display Images from SD Card Tutorial

public Object getItem(int position) { return position; } This class....something looks wrong...it shhould return an Object but it returns an int. im am getting this error

Ezio Auditore

Android Display Images from SD Card Tutorial