数组索引超出界限异常长度= 0;索引= 0

时间:2017-06-14 09:35:25

标签: java android arrays

我使用libaums来阅读文件。我只是从测试文件中复制。但如果我没有插上USB,就会给我一个错误。

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);
        }
    }

2 个答案:

答案 0 :(得分:1)

  

数组索引超出范围异常长度= 0;索引= 0

此行导致错误。你应该在获取第一个元素之前检查空数组。

 device = devices[0];

答案 1 :(得分:1)

它运行正常...只需添加抛出此ArrayIndexOutOfBoundsException。

$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\Extbase\\Object\\ObjectManager');
$querySettings = $objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);

$this->cityRepository->setDefaultQuerySettings($querySettings);
$cities = $this->cityRepository->findAll();

并通过以下方式调用:

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);
        }
    }

感谢codeRock