I'm trying to access the MediaStore.Images file using cursor but it keeps giving an error .
I tried creating an image object containing an array of images in the device, nd load it to the screen using Picasso library.
i created a function to get images after permission has been checked in the onCreate method.
private fun getAllImages(): ArrayList<Image>? {
val images = ArrayList<Image>()
val imagesUri =MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.Media.DISPLAY_NAME)
val cursor = [email protected](imagesUri,
projection, null, null, null)
try {
cursor!!.moveToFirst()
do {
val image = Image()
image.imagePath = cursor
.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
image.imageName = cursor.getString(cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DISPLAY_NAME))
images.add(image)
}while (cursor.moveToNext())
cursor.close()
}catch (e: Exception){
Log.e("PhotoGallery", "An error occured:$e")
Toast.makeText(this, "An error occured : $e", Toast.LENGTH_SHORT).show()
e.printStackTrace()
}
return images
}
This is where i called the method in the Main Activity
checkGalleryPermission()
phoneImages = ArrayList()
if(phoneImages!!.isEmpty()){
progressBar?.visibility = View.VISIBLE
phoneImages = getAllImages()
photoRecycler?.adapter = ImageAdapter(this, phoneImages!!)
photoRecycler?.layoutManager = GridLayoutManager(this,3)
photoRecycler?.setHasFixedSize(true)
progressBar?.visibility = View.GONE
}
But it keeps giving me this error
Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed) 2023-08-01 01:59:22.548 18765-18765 ek.photogallery com.secondweek.photogallery W Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed) 2023-08-01 01:59:22.837 18765-18765 PhotoGallery com.secondweek.photogallery E An error occured:android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 2023-08-01 01:59:22.837 18765-18765 Compatibil...geReporter com.secondweek.photogallery D Compat change id reported: 147798919; UID 10303; state: ENABLED 2023-08-01 01:59:22.848 18765-18765 Toast com.secondweek.photogallery V show: caller = com.secondweek.photogallery.MainActivity.getAllImages:83 2023-08-01 01:59:22.864 18765-18765 System.err com.secondweek.photogallery W android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0