2017-06-14 81 views
-6

我正在使用libaums來讀取文件。我只是從測試文件複製。但是如果我不插入USB,它會給我一個錯誤。數組索引超出界限例外長度= 0; index = 0

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 

這是我的代碼。

private void discoverDevice() { 
     UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); 
     UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(this); 
     device = devices[0]; 
     UsbDevice usbDevice = getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE); 
     if (usbDevice != null && usbManager.hasPermission(usbDevice)) { 
      Log.d(TAG, "received usb device via intent"); 
      setupDevice(); 
     } else { 
      PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); 
      usbManager.requestPermission(device.getUsbDevice(), permissionIntent); 
     } 
    } 
+3

此函數返回一個空數組:*** UsbMassStorageDevice.getMassStorageDevices(本); *** –

+2

它會拋出' java.lang.ArrayIndexOutOfBoundsException「,因爲它無法找到任何USB。所以'device = devices [0];'拋出這個異常。 – codeRock

+0

謝謝,它工作正常...只是添加引發此異常。 –

回答

1

數組索引越界異常長度= 0; index = 0

此行發生錯誤。在獲取第一個元素之前,您應該檢查空數組。

device = devices[0]; 
1

它工作正常......只是添加拋出此ArrayIndexOutOfBoundsException。

private void discoverDevice() throws ArrayIndexOutOfBoundsException{ 
     UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); 
     UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(this); 
     devicea = devices[0]; 
     UsbDevice usbDevice = getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE); 
     if (usbDevice != null && usbManager.hasPermission(usbDevice)) { 
      Log.d(TAG, "received usb device via intent"); 
      setupDevice(); 
     } else { 
      PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); 
      usbManager.requestPermission(devicea.getUsbDevice(), permissionIntent); 
     } 
    } 

,並調用它通過:

 try { 
      discoverDevice(); 
     } catch (ArrayIndexOutOfBoundsException e) { 
      e.printStackTrace(); 
     } 

感謝對codeRock

相關問題