I want to retrieve all the images from gallery from its database and want to display in my application in gridview. please tell how to do it..
Asked
Active
Viewed 2,887 times
1
-
1Do you want to retrieve images from gallery or database? – Shrikant Ballal Jun 04 '12 at 06:13
-
check out this tutorial :: http://vikaskanani.wordpress.com/2011/07/20/android-custom-image-gallery-with-checkbox-in-grid-to-select-multiple/ – Eight Jun 04 '12 at 06:35
2 Answers
2
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
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.OnItemLongClickListener;
/**
* Class will Display all gallery images in grid view This class has the
* functionality to move images from public gallery to Private
*
*/
public class AndroidGallery extends Activity implements OnItemLongClickListener {
private GridView sdcardImages;
private ImageAdapter imageAdapter;
private String TAG = this.getClass().getSimpleName();
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
private String thumb_Image_Path;
private String crypto = null;
private FileInputStream is = null;
private BufferedInputStream bis = null;
private Bitmap bitmap;
private ByteArrayOutputStream bytes;
private File galleryThumbFile, galleryImageFile,galleryThumbFolder, galleryImageFolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sdcard);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
photos.clear(); // If photos array list has any previous value then clear it
setViews(); // set views
setProgressBarIndeterminateVisibility(true);
sdcardImages.setAdapter(imageAdapter); // Fill adapter
loadImages(); // Load images from default gallery
}
/**
* Free up bitmap related resources.
*/
protected void onDestroy() {
super.onDestroy();
final GridView grid = sdcardImages;
final int count = grid.getChildCount();
ImageView v = null;
for (int i = 0; i < count; i++) {
v = (ImageView) grid.getChildAt(i);
((BitmapDrawable) v.getDrawable()).setCallback(null);
}
}
/**
* Load images...
*/
private void loadImages() {
final Object data = getLastNonConfigurationInstance();
if (data == null) {
new LoadImagesFromSDCard().execute();
} else {
final LoadedImage[] photos = (LoadedImage[]) data;
if (photos.length == 0) {
new LoadImagesFromSDCard().execute();
}
for (LoadedImage photo : photos) {
addImage(photo);
}
}
}
/**
* Load images from SD Card in the background, and display each image on the
* screen.
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
private class LoadImagesFromSDCard extends
AsyncTask<Object, LoadedImage, Object> {
@Override
protected Object doInBackground(Object... params) {
Uri uri = null;
Bitmap bitmap = null;
Bitmap newBitmap = null;
String[] projection = {MediaStore.Images.Thumbnails._ID};
Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int size = cursor.getCount();
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap,String.valueOf(imageID)));
}
}
} catch (IOException e) {
//Error fetching image, try to recover
Log.e(TAG, e.toString());
}
}
return null;
}
/**
* Add a new LoadedImage in the images grid.
*
* @param value
* The image.
*/
@Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
/**
* Set the visibility of the progress bar to false.
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Add image(s) to the grid view adapter.
*
* @param value
* Array of LoadedImages references
*/
private void addImage(LoadedImage... value) {
for (LoadedImage image : value) {
imageAdapter.addPhoto(image);
imageAdapter.notifyDataSetChanged();
}
}
/**
* Set view function will set views
*
*/
private void setViews() {
sdcardImages = (GridView) findViewById(R.id.sdcard);
sdcardImages.setOnItemLongClickListener(this); // Set Listener on GridView
imageAdapter = new ImageAdapter(getApplicationContext());
imageAdapter.notifyDataSetChanged();
}
/**
* Function will return bitmap of Gallery big image
* @param imagePath
* @return
*/
private Bitmap getImageBitmap(String imagePath) {
// TODO Auto-generated method stub
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis);
} catch (Exception e) {
// Try to recover
} finally {
try {
if (bis != null) {
bis.close();
}
if (is != null) {
is.close();
}
} catch (Exception e) {
}
}
System.gc();
return bitmap;
}
/** * Function will return thumb image of selected from gallery * @param thumbImagePath * @return */
private Bitmap getThumbnailBitmap(String thumbImagePath) {
try {
is = new FileInputStream(new File(thumbImagePath));
bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis);
} catch (Exception e) {
// Try to recover
} finally {
try {
if (bis != null) {
bis.close();
}
if (is != null) {
is.close();
}
} catch (Exception e) {
}
}
System.gc();
return bitmap;
}
}
/**
* This class is used for image adapter
* @author
*
*/
class ImageAdapter extends BaseAdapter {
private Context mContext;
ImageAdapter(Context context) {
mContext = context;
}
public void addPhoto(LoadedImage photo) {
photos.add(photo);
}
public int getCount() {
return photos.size();
}
public Object getItem(int position) {
return photos.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(90, 90));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(photos.get(position).getImage());
return imageView;
}
}
}
layout:
<?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:stretchMode="columnWidth"
android:gravity="center" android:layout_below="@id/RelativeWallTopBar"
android:numColumns="auto_fit" android:columnWidth="90dp"
android:horizontalSpacing="5dip" android:verticalSpacing="15dip" />

user1213202
- 1,305
- 11
- 23

Andy
- 5,379
- 7
- 39
- 53
0
Here I have taken main.xml, that contain one button and one Imageview. When I press the button images is displayed from the gallery and when I click on the image then it displayed in the imageview.
main.java
public class GalleryImagePickActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
ImageView imgBG;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgBG = (ImageView) findViewById(R.id.imgBG);
}
public void btnChooseBGClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PICTURE:
if (resultCode == RESULT_OK) {
Uri uri = imageReturnedIntent.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
Drawable d = new BitmapDrawable(yourSelectedImage);
imgBG.setBackgroundDrawable(d);
}
}
}
}
I hope it helps you.

Rahul Patel
- 3,823
- 5
- 30
- 46