-2

Please help me to get all Gallery in latest Android 10 devices.

xp Android
  • 109
  • 1
  • 9

1 Answers1

0

Here is the method to get list of gallery images. You can see DESC LIMIT 100 in code, here DESC means descending order and LIMIT 100 means it will pick 100 images from gallery. You can remove limit according to your requirement.

public void getGalleryImages(){
private ArrayList<GalleryBottomViewModel> listData=new ArrayList<GalleryBottomViewModel>();

final String[] columns = { MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_ADDED + " DESC LIMIT 100";

Cursor imagecursor  = mActivity.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,null, orderBy);

int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
int count = imagecursor.getCount();
Bitmap thumbnails = null;
String arrPath;
for (int i = 0; i <count; i++) {
    imagecursor.moveToPosition(i);
    int id = imagecursor.getInt(image_column_index);

    int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);

    if(mActivity!=null) {
        thumbnails = MediaStore.Images.Thumbnails.getThumbnail(mActivity.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KIND, null);
    }
    arrPath = imagecursor.getString(dataColumnIndex);

    GalleryBottomViewModel model=new GalleryBottomViewModel();
    model.setPath(arrPath);
    model.setBitmap(thumbnails);

    listData.add(model);

    if(mActivity!=null) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();

            }
        });
    }
}

imagecursor.close();

Log.d("size_gallery=",listData.size()+"");

}

Definitely this process will take some time so you cannot do it on main thread thats why you need asyncTask to load images in separate thread so application will not stuck.

class LoadingGalleryImages extends AsyncTask<Void,Void,Void>{


       @Override
       protected Void doInBackground(Void... voids) {
           if(mActivity!=null)
           getGalleryImages();
           return null;
       }

       @Override
       protected void onPostExecute(Void aVoid) {
           super.onPostExecute(aVoid);




       }

GalleryBottomViewModel:

public class GalleryBottomViewModel{

 private String path;
 private Bitmap bitmap;


    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
}
Muhammad Zahab
  • 1,049
  • 10
  • 21