Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 数组索引越界异常长度=0;索引=0_Java_Android_Arrays - Fatal编程技术网

Java 数组索引越界异常长度=0;索引=0

Java 数组索引越界异常长度=0;索引=0,java,android,arrays,Java,Android,Arrays,我正在用它来读取文件。我只是从测试文件中复制。但是如果我没有插上USB,它会给我一个错误 Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 这是我的密码 private void discoverDevice() { UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); Us

我正在用它来读取文件。我只是从测试文件中复制。但是如果我没有插上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);
        }
    }
数组索引越界异常长度=0;索引=0

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

 device = devices[0];

它工作得很好。。。只需添加即可将此ArrayIndex抛出BoundsException

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

感谢

这将返回一个空数组:UsbMassStorageDevice.getMassStorageDevices(this);它将抛出
java.lang.ArrayIndexOutOfBoundsException
,因为它找不到任何usb接口。So
device=devices[0]引发此异常。谢谢,它工作正常。。。只需添加即可抛出此异常。