0

I am trying to read thee content of a USB pendrive connected to the phone via otg cable. I can get the path of the pendrive but the listFiles() function returns null. No problem with the internal memory. I have specified also permissions. Why doesn't work?

// PERMISSIONS
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.usb.host"/>
<uses-permission android:name="android.permission.USB_PERMISSION"/>



// GET PENDRIVE PATH 
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
Map<String, UsbDevice> devices = usbManager.getDeviceList();

Map.Entry<String,UsbDevice> entry = devices.entrySet().iterator().next();
UsbDevice usbDevice = entry.getValue();

//PENDRIVE PATH
String path = usbDevice.getDeviceName();



File directory = new File(path);
File[] files = directory.listFiles();   // THIS IS NULL
Toast.makeText(getApplicationContext(), ""+files, Toast.LENGTH_SHORT).show();

//TRYING TO ITERATE ON A NULL OBJECT
for (File f : files)
    Toast.makeText(getApplicationContext(), f.getName(), Toast.LENGTH_SHORT).show();
Lorenzo
  • 11
  • 2
  • First, you don't have arbitrary read-write access to removable storage. Second, the device name isn't going to be a valid filesystem path (though it is possible that it will be part of such a path). – CommonsWare Nov 28 '19 at 16:28
  • How can I get the complete path of the pendrive? – Lorenzo Nov 29 '19 at 08:43
  • You can call `getExternalFilesDirs()`, `getExternalCacheDirs()`, and `getExternalMediaDirs()` to get locations that you can use. If those methods on `Context` return 2+ items, the second and subsequent ones are on removable storage, and that should include your pen drive. – CommonsWare Nov 29 '19 at 12:01

0 Answers0