在我的应用程序中,我使用了来自 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);
}