在我的应用程序中,我使用了来自BluetoothChat示例的类DeviceListActivity的略微修改版本。代码在我测试的所有设备上运行良好,但是当我发布应用程序时,我开始接收这样的报告:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1555)
at sword.games.highnoonf.activities.DeviceListActivity$1.onItemClick(DeviceListActivity.java:18 0)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3388)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1738)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5097)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
导致异常的函数是:
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
String devName = info.substring(0, info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
intent.putExtra("DEVICE_NAME", devName);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
其余代码几乎与DeviceListActivity示例相同...... 我希望有人可以解决这个问题,或者让我解释为什么会发生这种情况...... 谢谢......
编辑:代码已经检查名称是否存在,并且这些行的MAC地址长度是否正确(如果出现错误,手机未添加且用户无法点击它):
String name = device.getName();
String address = device.getAddress();
if(name == null) name = "Unknown";
else if (name.length() == 0) name = "Unknown";
if (address.length() == 17){
mNewDevicesArrayAdapter.add(name + "\n" + address);
}
答案 0 :(得分:0)
好像您的info.length()
小于 17 。确保 substring 方法不会将任何负值作为参数获取。将代码的关键部分放在 try / catch 块中以避免异常。