Last active
February 22, 2023 06:31
-
-
Save alirezanazari/249e8c1fe10f8d4ca41eb4def6e7bdca to your computer and use it in GitHub Desktop.
Fetch all photo or specific folder images in android - java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void getFolderPhotosById(Context context, String folderId, WeakReference<FetchListener<List<GalleryItemModel>>> callback) { | |
new Thread(() -> { | |
List<GalleryItemModel> photos = new ArrayList<>(); | |
if (context == null) { | |
if(callback.get() != null) callback.get().onFetch(photos); | |
return; | |
} | |
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; | |
String[] projection = { | |
MediaStore.MediaColumns.DATA, | |
MediaStore.Images.Media.DATE_TAKEN | |
}; | |
boolean isAllPhoto = folderId.equals("-1"); | |
//if received -1 as id means to fetch all photo and set null | |
//else set bucket id as folders id to fetch sub items | |
//order by date token to get newest items | |
Cursor cursor = context.getContentResolver().query( | |
uri, | |
projection, | |
isAllPhoto ? null : MediaStore.Images.Media.BUCKET_ID + " = ?", | |
isAllPhoto ? null : new String[]{folderId}, | |
MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC" | |
); | |
if (cursor != null) { | |
final int COLUMN_DATA = cursor.getColumnIndex(MediaStore.MediaColumns.DATA); | |
while (cursor.moveToNext()) { | |
try { | |
GalleryItemModel photo = new GalleryItemModel(); | |
photo.setId(photos.size()); | |
photo.setAddress(cursor.getString(COLUMN_DATA)); | |
if (photo.getAddress() != null && !photo.getAddress().contains(".gif")) { | |
photos.add(photo); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
cursor.close(); | |
} | |
if(callback.get() != null) callback.get().onFetch(photos); | |
}).start(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment