问题描述
我正在尝试从图库中获取所有图像并将它们显示在回收站视图中。为了获取图像,我正在使用 Paging 3 Library。当我从上到下滚动时,一切正常,所有图像都带有分页,但是当我向上滚动(从下到上)时,我只是卡在了一个循环中。 Paging3 一次又一次地获取相同的图像。
这是我的加载方法:
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)
}
}
这是我的 loadImagesFromStorage 函数:
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,"$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,e)
}
分页逻辑很简单,我第一次将光标移动到最后一个位置,它将是 -1,然后无论页面大小是多少,它都会根据该大小增加。 Cursor 获取数据,直到它有值并且光标位置小于 PageSize + Position。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)