Select Multiple Images from Android Gallery

Select multiple images from android gallery

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

intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

Your code above should look like this:

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"), 1);

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

How to select multiple images from android gallery separately

You missed this line:

intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

And activity result should be like this:

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST) {
if(resultCode == Activity.RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();

for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();
//TODO: do something; here is your selected images
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//TODO: do something
}
}
}

Intent:

       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 images"), PICK_IMAGE_REQUEST);

How to select multiple images from gallery in android?

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;
}

}

how to select multiple images in android

You should remove check "data.getData() != null", hope it's ok

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null) {

if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
Toast.makeText(getApplicationContext(), ""+mClipData.getItemCount(), Toast.LENGTH_SHORT).show();
} else if (data.getData() != null) {
Toast.makeText(getApplicationContext(), "One Image", Toast.LENGTH_SHORT).show();
}


}
}

How to select multiple images from gallery and display them in a single activity using android code?

I am very thankful to you that you suggested me to get multiple Uri of selected images.

The uris object was not created it was just declared in the above code as:

uris = new ArrayList<Uri>();

I didn't understand what was the exact problem but the following code able to fulfil my requirement:

package com.example.project1;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class Second_Activity3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button mButtonChooseImage;
List <String> list_of_products;
Spinner spino;
ImageView mImageView1;
ImageView mImageView2;
ImageView mImageView3;
ImageView mImageView4;
ImageView mImageView5;
ImageView mImageView6;
ProgressBar mProgressBar;
Uri mImageUri;
List<Uri> uris = null;
Button mButtonUpload;
StorageReference mStorageRef;
DatabaseReference mDatabaseRef;
private static final String TAG = "MainActivity";
private static final int PICK_IMAGE_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_3);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openFileChooser();
}
});

uris = new ArrayList<Uri>();

mImageView1 = findViewById(R.id.image_view1);
mImageView2 = findViewById(R.id.image_view2);
mImageView3 = findViewById(R.id.image_view3);
mImageView4 = findViewById(R.id.image_view4);
mImageView5 = findViewById(R.id.image_view5);
mImageView6 = findViewById(R.id.image_view6);

mButtonUpload = findViewById(R.id.button_upload);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("products");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("products");
} // Performing action when ItemSelected // from spinner, Overriding onItemSelected method
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // On selecting a spinner item
String item = parent.getItemAtPosition(position).toString(); // Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
// @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

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

// if (data.getClipData() != null) {
ClipData clipdata = data.getClipData();
for (int i=0; i<clipdata.getItemCount();i++)
{
uris.add(clipdata.getItemAt(i).getUri());
System.out.println("URL: "+clipdata.getItemAt(i).getUri());
}
// mImageUri = data.getData();
Picasso.with(this).load(uris.get(0)).into(mImageView1);
Picasso.with(this).load(uris.get(1)).into(mImageView2);
Picasso.with(this).load(uris.get(2)).into(mImageView3);
Picasso.with(this).load(uris.get(3)).into(mImageView4);
Picasso.with(this).load(uris.get(4)).into(mImageView5);
Picasso.with(this).load(uris.get(5)).into(mImageView6);

// }


}
}

Select multiple images from gallery

try this

 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"), 5);

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

if (requestCode == PICK_IMAGE_MULTIPLE) {

Log.e("++data", "" + data.getClipData().getItemCount());// Get count of image here.

Log.e("++count", "" + data.getClipData().getItemCount());

if (data.getClipData().getItemCount() > 5) {
adapter.notifyDataSetChanged();
Snackbar snackbar = Snackbar
.make(findViewById(R.id.btnSelectImg), "You can not select more than 15 images", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
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"), 5);
}
});
snackbar.setActionTextColor(Color.BLUE);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);
snackbar.show();

} else {
imagesUriArrayList.clear();

for (int i = 0; i < data.getClipData().getItemCount(); i++) {
imagesUriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
Log.e("SIZE", imagesUriArrayList.size() + "");
adapter = new DataAdapter(MainActivity.this, imagesUriArrayList);
imageresultRecycletview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

}
}

}

Load image like this

Bitmap bitmap=BitmapFactory.decodeFile(imagesUriArrayList.get(position));
bitmap = Bitmap.createScaledBitmap(bitmap,150, 150, true);
resultImageview.setImageBitmap(bitmap);

ask me in case of any query

Select multiple images from gallery and show in recyclerview

You can try something like,

Define your recyclerView and adapter like this,

ArrayList<Uri> uri = new ArrayList<>();
RecyclerView recyclerView;
HorizontalRecyclerView adapter;

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

recyclerView = findViewById(R.id.recyclerview);

adapter = new HorizontalRecyclerView(uri);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);

}

Step 1: Select multiple images from Gallery (can be inside an onClick)

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Pictures: "), 1);

Step 2: Once selected you need to extract the selected image's URI and store it in an ArrayList<Uri>

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
uri.add(data.getClipData().getItemAt(i).getUri());
}
adapter.notifyDataSetChanged();
}
} else if (data.getData() != null) {
String imagePath = data.getData().getPath();
}
}
}

Step 3: Make changes to your Adapter like this

public class HorizontalRecyclerView extends RecyclerView.Adapter<HorizontalRecyclerView.HorizontalViewHolder> {

private ArrayList<Uri> uri;

public HorizontalRecyclerView(ArrayList<Uri> uri) {
this.uri = uri;
}

@NonNull
@Override
public HorizontalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item, parent, false);
return new HorizontalViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull HorizontalViewHolder horizontalViewHolder, int position) {
horizontalViewHolder.mImageRecyclerView.setImageURI(uri.get(position));
}

@Override
public int getItemCount() {
return uri.size();
}

public class HorizontalViewHolder extends RecyclerView.ViewHolder {
ImageView mImageRecyclerView;

public HorizontalViewHolder(View itemView) {
super(itemView);
mImageRecyclerView = itemView.findViewById(R.id.imageView);
}
}
}

This should do the trick. Refer this link.



Related Topics



Leave a reply



Submit