0
val projection = arrayOf( MediaStore.Files.FileColumns.DISPLAY_NAME )
val selection  = MediaStore.Files.FileColumns.RELATIVE_PATH + " = '/'"

val mediaStoreVolumes = MediaStore.getExternalVolumeNames(requireActivity())
mediaStoreVolumes.forEach { volume ->
    val uri    = MediaStore.Files.getContentUri(volume)
    val cursor = cr.query(uri, projection, selection, null, null)
    if (cursor != null) {
        while (cursor.moveToNext()) {
            Log.e("Volume: "+volume, "File: "+ cursor.getString(0))
        }
        cursor.close()
    }
}

The above code print file names in 'external_primary' and SDCARD. But for USB OTG it fails with exception:

 E  FATAL EXCEPTION: main
 Process: com.starsolutions.starfilemanager, PID: 10093
 java.lang.IllegalArgumentException: Volume a80d-7c6d not found

But the volume name is returned by MediaStore by MediaStore.getExternalVolumeNames()

Is it possible to list files in a USB OTG drive using MediaStore API?

  • Which statement exactly causes the exception? – blackapps Jan 29 '23 at 08:50
  • val cursor = cr.query(uri, projection, selection, null, null). If the Uri is for external_primary or sdcard, there is no issue. – Muhammed naseef Koppilakkal Jan 29 '23 at 10:13
  • Did some tests and indeed we get an IllegalArgumentException querying the usb stick. Further i do not know if it should be possible. Before you can do a query() the MediaStore should first have scanned/indexed the usb stick... WIth SAF there are no problems. – blackapps Feb 01 '23 at 13:46
  • https://developer.android.com/training/data-storage/manage-all-files Quote: The MANAGE_EXTERNAL_STORAGE permission grants the following: ....`Access to the root directory of both the USB on-the-go (OTG) drive and the SD card.` But to no avail. Or i do not know what special to do for a stick. – blackapps Feb 01 '23 at 13:53

1 Answers1

0

This is a bug of Android 11. It fixed in android 12. https://issuetracker.google.com/u/0/issues/246857526