Select multiple images from android gallery with thumbnails

Hii Developer In This android tutorial, I am sharing how to select multiple images for the android gallery and show thumbnails. On a button click open a gallery and select multiple files for the gallery.  And show all select files in a list. and I user wants to remove any image to remove these.

How to select multiple images from the gallery in android? like whats App Facebook you select multiple files and upload to Facebook and whats App also. So In this file.  So let’s Start on Solution.

Start You Android Studio and Make a Project with Empty Screen And follow these Step by step to make your solution is an easy way.

Select multiple images from the android gallery with thumbnails.

Step 1: Main Screen XML file.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edit_text"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edComment"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="5dp"
        android:background="@drawable/edit_text"
        android:gravity="top"
        android:hint="Write your commetns hare"
        android:inputType="textMultiLine"
        android:padding="10dp" />

    <TextView
        android:id="@+id/buttonAttachment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/attach"
        android:drawablePadding="15dp"
        android:onClick="onClick"
        android:padding="15dp"
        android:text="Attach" />
</LinearLayout>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/newAttachmentList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

On button Attach ClickListener open Gallery and select multiple files you this method.
public void openFolder() {

    Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
    Intent intent = new Intent();
    intent.setType("*/*");
    intent.putExtra(Intent.EXTRA_STREAM,uri);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
}

After these use StartActivityFor Result to get the results of Intent for a gallery.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
        if (data.getClipData() != null) {
            int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
            for (int i = 0; i < count; i++) {
                Uri returnUri = data.getClipData().getItemAt(i).getUri();

                Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                returnCursor.moveToFirst();
                System.out.println("PIYUSH NAME IS" + returnCursor.getString(nameIndex));
                System.out.println("PIYUSH SIZE IS" + Long.toString(returnCursor.getLong(sizeIndex)));
                AttachmentListData attachmentListData = new AttachmentListData();
                attachmentListData.setImageName(returnCursor.getString(nameIndex));
                attachmentListData.setImageID(returnUri.toString());
                newAttachmentList.add(attachmentListData);

            }

        } else if (data.getData() != null) {
            Uri returnUri = data.getData();

            Cursor returnCursor =
                    getContentResolver().query(returnUri, null, null, null, null);
            int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
            returnCursor.moveToFirst();
            System.out.println("PIYUSH NAME IS" + returnCursor.getString(nameIndex));
            System.out.println("PIYUSH SIZE IS" + Long.toString(returnCursor.getLong(sizeIndex)));
            AttachmentListData attachmentListData = new AttachmentListData();
            attachmentListData.setImageName(returnCursor.getString(nameIndex));
            attachmentListData.setImageID(returnUri.toString());
            newAttachmentList.add(attachmentListData);
        }
        generateNewAttachmentList(newAttachmentList);
    }
}

 Step 2 Main Screen Java File Source code.

public class TicketDetailsActivity extends BaseActivity implements View.OnClickListener {
    private static final int PICK_FROM_GALLERY = 101;
  
    @BindView(R.id.buttonAttachment)
    TextView buttonAttachment;
    @BindView(R.id.newAttachmentList)
    RecyclerView newAttachmentListView;
    private ArrayList<AttachmentListData> newAttachmentList = new ArrayList<>();
    AttachmentListAdapter attachmentListAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tickets_details);
        ButterKnife.bind(this);
       
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonAttachment:
                openFolder();
                break;
        }

    }

    public void openFolder() {

        Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
        Intent intent = new Intent();
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_STREAM,uri);
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
            if (data.getClipData() != null) {
                int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
                for (int i = 0; i < count; i++) {
                    Uri returnUri = data.getClipData().getItemAt(i).getUri();

                    Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
                    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                    returnCursor.moveToFirst();
                    System.out.println("PIYUSH NAME IS" + returnCursor.getString(nameIndex));
                    System.out.println("PIYUSH SIZE IS" + Long.toString(returnCursor.getLong(sizeIndex)));
                    AttachmentListData attachmentListData = new AttachmentListData();
                    attachmentListData.setImageName(returnCursor.getString(nameIndex));
                    attachmentListData.setImageID(returnUri.toString());
                    newAttachmentList.add(attachmentListData);

                }

            } else if (data.getData() != null) {
                Uri returnUri = data.getData();

                Cursor returnCursor =
                        getContentResolver().query(returnUri, null, null, null, null);
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                returnCursor.moveToFirst();
                System.out.println("PIYUSH NAME IS" + returnCursor.getString(nameIndex));
                System.out.println("PIYUSH SIZE IS" + Long.toString(returnCursor.getLong(sizeIndex)));
                AttachmentListData attachmentListData = new AttachmentListData();
                attachmentListData.setImageName(returnCursor.getString(nameIndex));
                attachmentListData.setImageID(returnUri.toString());
                newAttachmentList.add(attachmentListData);
            }
            generateNewAttachmentList(newAttachmentList);
        }
    }

    private void generateNewAttachmentList(ArrayList<AttachmentListData> newAttachmentList) {
        newAttachmentListView.setHasFixedSize(true);
        LinearLayoutManager MyLayoutManager = new LinearLayoutManager(TicketDetailsActivity.this);
        MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        newAttachmentListView.setLayoutManager(MyLayoutManager);
        attachmentListAdapter = new AttachmentListAdapter(newAttachmentList, TicketDetailsActivity.this);
        newAttachmentListView.setAdapter(attachmentListAdapter);
    }

Step 3 Create a Card Layout XML file for Show attach Thumblaine file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ticketNumberCardView"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    card_view:cardBackgroundColor="@color/White"
    card_view:cardCornerRadius="2dp"
    android:layout_margin="5dp">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <ImageView
            android:id="@+id/attachedImageId"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentLeft="true"
            android:src="@android:drawable/ic_menu_close_clear_cancel"
            android:layout_centerVertical="true"/>

        <TextView
            android:id="@+id/attachedImageName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/attachedImageId"
            android:layout_toLeftOf="@id/cancelAttachment"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:fontFamily="@font/roboto_regular"
            android:text="The notes on the new age cloud system"
            android:textAppearance="@style/small_body"
            android:layout_centerVertical="true"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_close_clear_cancel"
            android:id="@+id/cancelAttachment"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>
</androidx.cardview.widget.CardView>

Step 4 Create an Adapter class to Set the image and title on the card list view.  

public class AttachmentListAdapter extends RecyclerView.Adapter<AttachmentListAdapter.AttachmentListViewHolder> {
    public ArrayList<AttachmentListData> newAttachmentList;
    public Activity mActivity;


    public AttachmentListAdapter(ArrayList<AttachmentListData> list, Activity activity) {
        newAttachmentList = list;
        mActivity = activity;
    }

    @Override
    public AttachmentListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_newattachment_list, parent, false);

        AttachmentListViewHolder holder = new AttachmentListViewHolder(view, mActivity, newAttachmentList);

        return holder;
    }

    @Override
    public void onBindViewHolder(final AttachmentListViewHolder holder, int position) {
        holder.attachedImageName.setText((newAttachmentList.get(position).getImageName()));
        String userImage = newAttachmentList.get(position).getImageID();
        if (userImage.isEmpty()||userImage.equals(null)||userImage.equals("")) {

        } else {
            Picasso.with(mActivity)
                    .load(userImage)
                    .placeholder(R.drawable.app_logo)
                    .fit().centerCrop()
                    .into( holder.attachedImageId);
        }
    }

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

    class AttachmentListViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.attachedImageId)
        ImageView attachedImageId;
        @BindView(R.id.attachedImageName)
        TextView attachedImageName;
        @BindView(R.id.cancelAttachment)
        ImageView cancelAttachment;



        public AttachmentListViewHolder(View view, final Activity activity, ArrayList<AttachmentListData> attachmentList) {
            super(view);
            ButterKnife.bind(this, view);
            cancelAttachment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = getAdapterPosition();
                    attachmentList.remove(pos);
                    notifyDataSetChanged();
                }
            });
        }
    }
}

Step 5:  Create a DataObject java Class for getter and setter.

public class AttachmentListData implements Parcelable {
    private String imageName;

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public String getImageID() {
        return imageID;
    }

    public void setImageID(String imageID) {
        this.imageID = imageID;
    }

    private String imageID;

    public static final Creator CREATOR = new Creator() {
        public AttachmentListData createFromParcel(Parcel in) {
            return new AttachmentListData(in);
        }

        public AttachmentListData[] newArray(int size) {
            return new AttachmentListData[size];
        }
    };




    public AttachmentListData() {
    }

    public AttachmentListData(Parcel in) {
        super();
        readFromParcel(in);
    }



    public void readFromParcel(Parcel in) {
        imageName = in.readString();
        imageID = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(imageName);
        dest.writeString(imageID);
    }
}

 

Facebooktwitterredditpinterestlinkedinmail