Search code examples
androidandroid-gallery

Showing images of gallery in my application


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


Solution

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