Tutorial details

Android – Select multiple photos from Gallery | App Code for Sale | Preview

Android – Select multiple photos from Gallery | Android Tutorial

How to select multiple photos from Photo Gallery

Overview PAGE TOP

Today i am going to discuss about implementation of selecting multiple photos from Photo Gallery. You know, i have searched enough to find out a solution for selecting multiple images from android’s native gallery. There are 2 ways to implement multi selection of images in gallery:

1) Intent for getting multiple images

2) Define custom gallery with fetching and loading photos from native gallery.

uji.png

1. Intent for getting multiple images: PAGE TOP

As being native lover, i tried to find out a solution by implementing solution provided same like we select single image from gallery, by using below code:

1   Intent intent = new Intent();
2   intent.setType('image/*');
3   intent.setAction(Intent.ACTION_GET_CONTENT);
4   startActivityForResult(Intent.createChooser(intent, 'Select Picture'), PICK_IMAGE);

But i am unable to implement a solution for selecting multiple images using the above way. Yes i came to know we can use SEND_MULTIPLE intent but i am sure how do we implement this and select mutiple images. I will try to implement it and share with you if i will get success.

2. Define custom gallery with fetching and loading photos from native gallery: PAGE TOP

As we dont know about the Intent way solution, this is the good idea for selecting multiple photos. One of my friend Vikas Kanani is already done with this solution earlier. I did thorough testing and came to know about the below issues:

  1. Images are loading very slow if we are having larger number of images, lets say 2000-5000
  2. Crashing if we load more images

For resolving above issues, what i did? I have implemented Asynchronous image loading so that every image gets loaded asynchronously.

kau.png

Now, lets implement improved solution

Step 1: Download Image loader library from Here.

Step 2: Add the library inside the libs folder, right click on the jar file -> Select Add to Build Path

gt.png

Step 3: Define row layout for image item rowmultiphotoitem.xml

01  <?xml version='1.0' encoding='utf-8'?>
02  <RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android'
03      android:layout_width='fill_parent'
04      android:layout_height='fill_parent' >
05  
06      <ImageView
07          android:id='@+id/imageView1'
08          android:layout_width='100dp'
09          android:layout_height='100dp'
10          android:src='@drawable/ic_launcher' />
11  
12      <CheckBox
13          android:id='@+id/checkBox1'
14          android:layout_width='wrap_content'
15          android:layout_height='wrap_content'
16          android:layout_alignRight='@+id/imageView1'
17          android:layout_centerVertical='true'/>
18  
19  </RelativeLayout>

Step 4: Define activity layout with GridView acimagegrid.xml

01  <?xml version='1.0' encoding='utf-8'?>
02  <RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android'
03      android:layout_width='fill_parent'
04      android:layout_height='fill_parent' >
05  
06      <GridView
07          android:id='@+id/gridview'
08          android:layout_width='fill_parent'
09          android:layout_height='fill_parent'
10          android:columnWidth='100dip'
11          android:gravity='center'
12          android:horizontalSpacing='4dip'
13          android:numColumns='auto_fit'
14          android:stretchMode='columnWidth'
15          android:layout_above='@+id/button1'
16          android:verticalSpacing='2dip' />
17  
18      <Button
19          android:id='@+id/button1'
20          android:layout_alignParentBottom='true'
21          android:layout_width='wrap_content'
22          android:layout_height='wrap_content'
23          android:layout_centerHorizontal='true'
24          android:onClick='btnChoosePhotosClick'
25          android:text='Select Photos' />
26  
27  </RelativeLayout>

Step 5: Define a UILApplication to declare application level configuration settings UILApplication.java

01  package com.technotalkative.multiphotoselect;
02  
03  import android.app.Application;
04  
05  import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
06  import com.nostra13.universalimageloader.core.ImageLoader;
07  import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
08  
09  /**
10   * @author Paresh Mayani (@pareshmayani)
11   */
12  public class UILApplication extends Application {
13  
14   @Override
15   public void onCreate() {
16    super.onCreate();
17  
18    // This configuration tuning is custom. You can tune every option, you may tune some of them,
19    // or you can create default configuration by
20    //  ImageLoaderConfiguration.createDefault(this);
21    // method.
22    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
23     .threadPoolSize(3)
24     .threadPriority(Thread.NORM_PRIORITY - 2)
25     .memoryCacheSize(1500000) // 1.5 Mb
26     .denyCacheImageMultipleSizesInMemory()
27     .discCacheFileNameGenerator(new Md5FileNameGenerator())
28     .enableLogging() // Not necessary in common
29     .build();
30    // Initialize ImageLoader with configuration.
31    ImageLoader.getInstance().init(config);
32   }
33  }

Step 6: Define a base activity to create a singleton instance of ImageLoader class. BaseActivity.java

01  package com.technotalkative.multiphotoselect;
02  
03  import android.app.Activity;
04  
05  import com.nostra13.universalimageloader.core.ImageLoader;
06  
07  /**
08   * @author Paresh Mayani (@pareshmayani)
09   */
10  public abstract class BaseActivity extends Activity {
11  
12   protected ImageLoader imageLoader = ImageLoader.getInstance();
13  
14  }

Step 7: Now, Its time to define a main activity where we can write a logic for fetching photos from native gallery. Here i have also defined an ImageAdapter for the GridView. MultiPhotoSelectActivity.java

001 package com.technotalkative.multiphotoselect;
002 
003 import java.util.ArrayList;
004 
005 import android.content.Context;
006 import android.database.Cursor;
007 import android.graphics.Bitmap;
008 import android.os.Bundle;
009 import android.provider.MediaStore;
010 import android.util.Log;
011 import android.util.SparseBooleanArray;
012 import android.view.LayoutInflater;
013 import android.view.View;
014 import android.view.ViewGroup;
015 import android.view.animation.Animation;
016 import android.view.animation.AnimationUtils;
017 import android.widget.BaseAdapter;
018 import android.widget.CheckBox;
019 import android.widget.CompoundButton;
020 import android.widget.Toast;
021 import android.widget.CompoundButton.OnCheckedChangeListener;
022 import android.widget.GridView;
023 import android.widget.ImageView;
024 
025 import com.nostra13.universalimageloader.core.DisplayImageOptions;
026 import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
027 
028 /**
029  * @author Paresh Mayani (@pareshmayani)
030  */
031 public class MultiPhotoSelectActivity extends BaseActivity {
032 
033  private ArrayList<String> imageUrls;
034  private DisplayImageOptions options;
035  private ImageAdapter imageAdapter;
036 
037  @Override
038  public void onCreate(Bundle savedInstanceState) {
039   super.onCreate(savedInstanceState);
040   setContentView(R.layout.ac_image_grid);
041 
042   final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
043   final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
044   Cursor imagecursor = managedQuery(
045     MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
046     null, orderBy + ' DESC');
047 
048   this.imageUrls = new ArrayList<String>();
049 
050   for (int i = 0; i < imagecursor.getCount(); i++) {
051    imagecursor.moveToPosition(i);
052    int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
053    imageUrls.add(imagecursor.getString(dataColumnIndex));
054 
055    System.out.println('=====> Array path => '+imageUrls.get(i));
056   }
057 
058   options = new DisplayImageOptions.Builder()
059    .showStubImage(R.drawable.stub_image)
060    .showImageForEmptyUri(R.drawable.image_for_empty_url)
061    .cacheInMemory()
062    .cacheOnDisc()
063    .build();
064 
065   imageAdapter = new ImageAdapter(this, imageUrls);
066 
067   GridView gridView = (GridView) findViewById(R.id.gridview);
068   gridView.setAdapter(imageAdapter);
069   //gridView.setOnItemClickListener(new OnItemClickListener() {
070   // @Override
071   //public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
072   // startImageGalleryActivity(position);
073   // }
074   //});
075    
076  }
077 
078  @Override
079  protected void onStop() {
080   imageLoader.stop();
081   super.onStop();
082  }
083 
084  public void btnChoosePhotosClick(View v){
085 
086   ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
087   Toast.makeText(MultiPhotoSelectActivity.this, 'Total photos selected: '+selectedItems.size(), Toast.LENGTH_SHORT).show();
088   Log.d(MultiPhotoSelectActivity.class.getSimpleName(), 'Selected Items: ' + selectedItems.toString());
089  }
090 
091  /*private void startImageGalleryActivity(int position) {
092   Intent intent = new Intent(this, ImagePagerActivity.class);
093   intent.putExtra(Extra.IMAGES, imageUrls);
094   intent.putExtra(Extra.IMAGE_POSITION, position);
095   startActivity(intent);
096  }*/
097 
098  public class ImageAdapter extends BaseAdapter {
099 
100   ArrayList<String> mList;
101   LayoutInflater mInflater;
102   Context mContext;
103   SparseBooleanArray mSparseBooleanArray;
104 
105   public ImageAdapter(Context context, ArrayList<String> imageList) {
106    // TODO Auto-generated constructor stub
107    mContext = context;
108    mInflater = LayoutInflater.from(mContext);
109    mSparseBooleanArray = new SparseBooleanArray();
110    mList = new ArrayList<String>();
111    this.mList = imageList;
112 
113   }
114 
115   public ArrayList<String> getCheckedItems() {
116    ArrayList<String> mTempArry = new ArrayList<String>();
117 
118    for(int i=0;i<mList.size();i++) {
119     if(mSparseBooleanArray.get(i)) {
120      mTempArry.add(mList.get(i));
121     }
122    }
123 
124    return mTempArry;
125   }
126 
127   @Override
128   public int getCount() {
129    return imageUrls.size();
130   }
131 
132   @Override
133   public Object getItem(int position) {
134    return null;
135   }
136 
137   @Override
138   public long getItemId(int position) {
139    return position;
140   }
141 
142   @Override
143   public View getView(int position, View convertView, ViewGroup parent) {
144 
145    if(convertView == null) {
146     convertView = mInflater.inflate(R.layout.row_multiphoto_item, null);
147    }
148 
149    CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
150    final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
151 
152    imageLoader.displayImage('file://'+imageUrls.get(position), imageView, options, newSimpleImageLoadingListener() {
153     @Override
154     public void onLoadingComplete(Bitmap loadedImage) {
155      Animation anim = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this, R.anim.fade_in);
156      imageView.setAnimation(anim);
157      anim.start();
158     }
159    });
160 
161    mCheckBox.setTag(position);
162    mCheckBox.setChecked(mSparseBooleanArray.get(position));
163    mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
164 
165    return convertView;
166   }
167 
168   OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
169 
170    @Override
171    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
172     // TODO Auto-generated method stub
173     mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
174    }
175   };
176  }
177 }

Download this example from here: Android – Select multiple photos from Gallery

Reference PAGE TOP

http://www.javacodegeeks.com/2012/10/android-select-multiple-photos-from-gallery.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.