I am trying to get all the Images from Gallery and displaying them in a recycler view. To fetch images I am using Paging 3 Library. Everything is working fine when I am scrolling from Top to Bottom I am getting all the images with pagination but when I scroll up (Bottom to Top) I just stuck inside a loop. Paging3 fetches the same images again and again.
Here is my load method:
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ImagesData> {
val position = params.key ?: STARTING_PAGE_INDEX
return try {
val photos : ArrayList<ImagesData> = ArrayList()
imagesDataSource.loadImagesFromStorage(position, params.loadSize).collect {
photos.addAll(it)
}
LoadResult.Page(
data = photos,
prevKey = if (position == STARTING_PAGE_INDEX) null else position,
nextKey = if (photos.isEmpty()) null else position + params.loadSize
)
} catch (exception: Exception) {
LoadResult.Error(exception)
}
}
and this is my loadImagesFromStorage function:
suspend fun loadImagesFromStorage(
prevIndex : Int,
pageSize : Int
) : Flow<List<ImagesData>> = flow {
val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor?
val columnIndexId: Int
val listOfAllImages = mutableListOf<ImagesData>()
val projection = arrayOf(MediaStore.Images.Media._ID)
val orderBy = MediaStore.Images.Media.DATE_TAKEN
try {
cursor = context.contentResolver
.query(
uri,
projection,
null,
null,
"$orderBy DESC")
cursor?.let {
cursor.moveToPosition(prevIndex)
columnIndexId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
while (cursor.moveToNext() && cursor.position < (prevIndex + pageSize)){
val contentUri = ContentUris.withAppendedId(uri, cursor.getLong(columnIndexId))
listOfAllImages.add(ImagesData(contentUri))
}
cursor.close()
}
} catch (e : Exception) {
Log.e(TAG, "loadImagesFromStorage: ",e )
}
emit(listOfAllImages)
}.flowOn(Dispatchers.IO).catch { e ->
Log.e(TAG, "loadImagesFromStorage: ", e)
}
Pagination logic is simple I am moving my cursor to the last position for the first time it is going to be -1 and then whatever the page Size is it will increase according to that size. and Cursor fetches the data until it has values and the cursor position is less than the PageSize + Position.