21

I am making a project in which i want to select multiple photos from gallery and want to save that in imageview array. I am able to import single image and save at imageview Can anyone tell please how may i import multiple images and save in array or different imageviews?

MainActivity extends Activity implements OnClickListener {

    Button addphoto, save;
    ImageView img1[];
    Bitmap yourbitmap, resized;
    int RESULT_LOAD_IMAGE1 =1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addphoto = (Button)findViewById(R.id.add);
        img1[0] = (ImageView)findViewById(R.id.imageView1);
        save = (Button)findViewById(R.id.save);
        addphoto.setOnClickListener(this);
        save.setOnClickListener(this);
    }
@Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch(arg0.getId()){
        case R.id.add:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE1);
            break;
            }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE1 && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            try {
                yourbitmap = BitmapFactory.decodeFile(picturePath);
                resized=    Bitmap.createScaledBitmap(yourbitmap, 200,300, true);


                img1[0].setImageBitmap(resized);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }



    }

}
nawaab saab
  • 1,892
  • 2
  • 20
  • 36

8 Answers8

42

Implement custom gallery selector with below code :

activity_main

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" android:id="@+id/scroll1"
    >

    <LinearLayout
        android:id="@+id/lnrImages"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>
</ScrollView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:id="@+id/linearLayout">
    <Button
        android:id="@+id/btnAddPhots"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Add Phots"/>

    <Button
        android:id="@+id/btnSaveImages"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Save"/>
</LinearLayout>

custom_gallery

<?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:gravity="center"
    android:orientation="vertical">
    <GridView
        android:id="@+id/grdImages"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:columnWidth="90dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>

    <Button
        android:id="@+id/btnSelect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select"
        android:layout_marginTop="5dp"/>

</LinearLayout>

custom_gallery_item

    <ImageView
        android:id="@+id/imgThumb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <CheckBox
        android:id="@+id/chkImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|right"/>
</FrameLayout>

MainActivity

public class MainActivity extends Activity implements View.OnClickListener{

    private LinearLayout lnrImages;
    private Button btnAddPhots;
    private Button btnSaveImages;
    private ArrayList<String> imagesPathList;
    private Bitmap yourbitmap;
    private Bitmap resized;
    private final int PICK_IMAGE_MULTIPLE =1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lnrImages = (LinearLayout)findViewById(R.id.lnrImages);
        btnAddPhots = (Button)findViewById(R.id.btnAddPhots);
        btnSaveImages = (Button)findViewById(R.id.btnSaveImages);
        btnAddPhots.setOnClickListener(this);
        btnSaveImages.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnAddPhots:
                Intent intent = new Intent(MainActivity.this,CustomPhotoGalleryActivity.class);
                startActivityForResult(intent,PICK_IMAGE_MULTIPLE);
                break;
            case R.id.btnSaveImages:
                if(imagesPathList !=null){
                    if(imagesPathList.size()>1) {
                        Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(MainActivity.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(MainActivity.this," no images are selected", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if(requestCode == PICK_IMAGE_MULTIPLE){
                imagesPathList = new ArrayList<String>();
                String[] imagesPath = data.getStringExtra("data").split("\\|");
                try{
                    lnrImages.removeAllViews();
                }catch (Throwable e){
                    e.printStackTrace();
                }
                for (int i=0;i<imagesPath.length;i++){
                    imagesPathList.add(imagesPath[i]);
                    yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
                    ImageView imageView = new ImageView(this);
                    imageView.setImageBitmap(yourbitmap);
                    imageView.setAdjustViewBounds(true);
                    lnrImages.addView(imageView);
                }
            }
        }

    }

}

CustomPhotoGalleryActivity

 public class CustomPhotoGalleryActivity extends Activity {

    private GridView grdImages;
    private Button btnSelect;

    private ImageAdapter imageAdapter;
    private String[] arrPath;
    private boolean[] thumbnailsselection;
    private int ids[];
    private int count;


    /**
     * Overrides methods
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_gallery);
        grdImages= (GridView) findViewById(R.id.grdImages);
        btnSelect= (Button) findViewById(R.id.btnSelect);

        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        @SuppressWarnings("deprecation")
        Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.arrPath = new String[this.count];
        ids = new int[count];
        this.thumbnailsselection = new boolean[this.count];
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            ids[i] = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            arrPath[i] = imagecursor.getString(dataColumnIndex);
        }

        imageAdapter = new ImageAdapter();
        grdImages.setAdapter(imageAdapter);
        imagecursor.close();


        btnSelect.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                final int len = thumbnailsselection.length;
                int cnt = 0;
                String selectImages = "";
                for (int i = 0; i < len; i++) {
                    if (thumbnailsselection[i]) {
                        cnt++;
                        selectImages = selectImages + arrPath[i] + "|";
                    }
                }
                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
                } else {

                    Log.d("SelectedImages", selectImages);
                    Intent i = new Intent();
                    i.putExtra("data", selectImages);
                    setResult(Activity.RESULT_OK, i);
                    finish();
                }
            }
        });
    }
    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        super.onBackPressed();

    }

    /**
     * Class method
     */

    /**
     * This method used to set bitmap.
     * @param iv represented ImageView 
     * @param id represented id
     */

    private void setBitmap(final ImageView iv, final int id) {

        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... params) {
                return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                iv.setImageBitmap(result);
            }
        }.execute();
    }


    /**
     * List adapter
     * @author tasol
     */

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

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

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

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.custom_gallery_item, null);
                holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
                holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.chkImage.setId(position);
            holder.imgThumb.setId(position);
            holder.chkImage.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]) {
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            holder.imgThumb.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    int id = holder.chkImage.getId();
                    if (thumbnailsselection[id]) {
                        holder.chkImage.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        holder.chkImage.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            try {
                setBitmap(holder.imgThumb, ids[position]);
            } catch (Throwable e) {
            }
            holder.chkImage.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }


    /**
     * Inner class
     * @author tasol
     */
    class ViewHolder {
        ImageView imgThumb;
        CheckBox chkImage;
        int id;
    }

}
Kushal
  • 8,100
  • 9
  • 63
  • 82
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • do i have to create **CustomPhotoGalleryActivity** in other java class file? – nawaab saab May 02 '14 at 17:06
  • 1
    @HareshChhelana: Your code is really helpful for all.. Thank you for wonderful post.. !! – Kushal Aug 03 '15 at 06:15
  • I didn't test this code but here is some issues `ScrollView` can't have more than 1 child view you have made two and your custom_gallery_item don't have root element. Please update your code in correct way. – androidXP Oct 23 '16 at 10:11
  • @HareshChhelana How to filter opened intent (to choose images) to just show jpg images? – Dr.jacky Oct 29 '16 at 08:34
  • I have created new library for custom image picker with more feature in Github check out this : https://github.com/HareshChhelana/CustomGalleryPickerForAndroid hope it help some one. – Haresh Chhelana Mar 31 '17 at 07:37
  • @Haresh Chhelana I also tried the similar concept but when the number of image is larger than 100 say, then it tells to wait or exit. (some what like it crash) is there any solution there. – Dilip Poudel Apr 20 '17 at 05:55
  • 4
    @DilipPoudel Check out this https://github.com/HareshChhelana/CustomGalleryPickerForAndroid – Haresh Chhelana Apr 21 '17 at 13:09
  • Yes, add CustomPhotoGalleryActivity in other java class, also don't forget to add permission – CGR Oct 10 '17 at 18:08
  • @HareshChhelana Can it be used as MultiVideoSelector instead of images? – CGR Oct 10 '17 at 22:03
  • @CGR I haven't try yet you can try and let us know is working or not. – Haresh Chhelana Oct 11 '17 at 04:57
22

There is EXTRA_ALLOW_MULTIPLE option is set on the intent through the Intent.putExtra() method:

  intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

In your code write as below:

Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), RESULT_LOAD_IMAGE1);

Note: the EXTRA_ALLOW_MULTIPLE option is only available in Android API 18 and higher.

If you want to develop your own gallery then check out the Select Multiple Images from Gallery

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
6

Here is the code for Select Multiple Image and video from Default Gallery.

Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent();
            i.setType("image/*");
       //i.setType("video/*");
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            i.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(i, "android.intent.action.SEND_MULTIPLE"), 1);
        }
    });

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

    System.out.println("++data" + data.getClipData().getItemCount());// Get count of image here.

        System.out.println("++count" + data.getClipData().getItemCount());
        Uri selectedImage = data.getClipData().getItemAt(0).getUri();//As of now use static position 0 use as per itemcount.
        Bitmap bitmap = null;
  //        Uri selectedImage1 = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("+++ clipdate" + selectedImage);

        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(bitmap);
    //        }

}
Roadies
  • 3,309
  • 2
  • 30
  • 46
6

Complete Working Answer

Intent

Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);

Activity Result

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            // When an Image is picked
            if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
                    && null != data && null != data.getClipData()) {
    
                ClipData mClipData = data.getClipData();
    
                Toast.makeText(getActivity(), "You picked " +
                                (mClipData.getItemCount() > 1 ? mClipData.getItemCount() + "Images" :
                                        mClipData.getItemCount() + "Image"),
                        Toast.LENGTH_LONG).show();
    
                pickedImageContainer.removeAllViews();
    
                int pickedImageCount;
    
                for (pickedImageCount = 0; pickedImageCount < mClipData.getItemCount();
                     pickedImageCount++) {
    
                    ImageView productImageView =
                            new ImageView(getActivity());
    
                    productImageView.setAdjustViewBounds(true);
    
                    productImageView.setScaleType(ImageView.ScaleType.FIT_XY);
    
                    productImageView.setLayoutParams(new LinearLayout
                            .LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT));
    
                    pickedImageContainer.addView(productImageView);
    
                    Glide.with(getActivity())
                            .load(mClipData.getItemAt(pickedImageCount).getUri())
                            .fitCenter().placeholder(R.drawable.map_default)
                            .error(R.drawable.map_default)
                            .into(productImageView);
                }
            } else {
                Toast.makeText(getActivity(), "You haven't picked any Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(getActivity(), "Error: Something went wrong " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
sai Pavan Kumar
  • 1,129
  • 12
  • 20
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
  • You correct,but I have to switch glide down under add view, the project can run successfully – Doan Bui May 07 '18 at 07:30
  • Almost works for me. Gallery does not allow me to actually make selections (though it is invoked), unless I use the action ACTION_GET_CONTENT. – JASON G PETERSON Jul 20 '19 at 10:20
2

I think android does not support selecting multiple images. For that need to use some library. i was also stuck in the same

https://github.com/luminousman/MultipleImagePick

this one helped me.

0
This is manifest file code for app to get consider you are sending images to your app

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                 <action
                android:name="android.intent.action.SEND_MULTIPLE" />
                 <action
                android:name="android.intent.action.SEND" />
            <category
                android:name="android.intent.category.DEFAULT" />
            <data
                android:mimeType="image/*" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Program code...

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d("MainActivity", "on Create ");

        if (Intent.ACTION_SEND_MULTIPLE.equals(getIntent().getAction())&& getIntent().hasExtra(Intent.EXTRA_STREAM))
        {
                ArrayList<Parcelable> list =
                        getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                            for (Parcelable parcel : list) {
                               Uri uri1 = (Uri) parcel;
                               Log.d("MainActivity", "on Create uri1 " + uri1);
                               String sourcepath=getPath(uri1);
                               Log.d("MainActivity", "on Create sourcepath " + sourcepath);
                               /// do things here with each image source path.
                           }
                            //Commented by Aishwary coz I want to open the app after selecting images otherwise uncomment to just select 
                            //finish();
            }else{
                // This part is of single image by Aishwary
                Uri imageUri =(Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
                Log.d("MainActivity", "on Create ImageUri " + imageUri);
            }
            }

    public  String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        startManagingCursor(cursor);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
        }

    }

This will allow you to get source path and images url . Now you can make array for url and use this url as you want...
0
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case SELECT_PICTURE:
                    Uri selectedImageUri = data.getData();
                    imgPerview.setBackgroundColor(Color.TRANSPARENT);
                    LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                    imgPerview.setLayoutParams(vp);
                    imgPerview.setScaleType(ImageView.ScaleType.FIT_XY);
                    imgPerview.setImageURI(selectedImageUri);
                    uri = selectedImageUri;
            }
        }
        catch (Exception ex)
        {}
    }

sai Pavan Kumar
  • 1,129
  • 12
  • 20
Saeed Parand
  • 33
  • 1
  • 1
  • 9
0

You can use Uri of images to store their location in MainActivity.java

ArrayList<Uri> Images = new ArrayList<>();
...
...


public void PickImagesIntent(){
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGES);
}

   
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_IMAGES) {
            if (data.getClipData() != null) {
                ClipData mClipData = data.getClipData();
                for (int i = 0; i < mClipData.getItemCount(); i++) {
                    ClipData.Item item = mClipData.getItemAt(i);
                    Uri imageUri = item.getUri();
                    Images.add(imageUri);
                }
            } else if (data.getData() != null) {
                Uri imageUri = data.getData();
                Images.add(uri);
            }
        }
    }
}

You can send it to another class(ViewImage.java) in form of string

Intent ImageIntent = new Intent(this,ViewImage.class);
ImageIntent.putExtra("imageUri",Images.get(i).toString());
stratActivity(ImageIntent);

To receive it in another class(ViewImage.java)

Intent intent = getIntent();
String imageUriString = intent.getStringExtra("imageUri");
Uri uri = Uri.parse(imageUriSrting);

To set it to ImageView

ImageView imageView = (ImageView)findViewById(##id##);
imageView.setImageURI(uri);