Most of the time while working in the android the most commonly faced problem for the developers is how to pick up the files or images from the phone memory or the SDCard , to be used further in the project.In this short tutorial followed by source code we will provide the working example ,demonstrating how to pick image in an android application and display it on screen.

  1. Create a New Project with only one activity
  2. Change the activity_main.xml layout file as per following listing

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/BTNPickImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="pickImage"
android:text="PickImage" >
</Button>
<ImageView
android:id="@+id/Imgresult"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/icon" >
</ImageView>
</LinearLayout>


3. Add the code in the activity class


package com.test.android.imagepickExample;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class ImagePickActivity extends Activity {

private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;

 

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.Imgresult);

}

public void pickImage(View View) {

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}

stream =getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
imageView.setImageBitmap(bitmap);

} catch (FileNotFoundException e) {

e.printStackTrace();

} finally {

if (stream != null)
try {

stream.close();

} catch (IOException e) {

e.printStackTrace();

}
}
}
}