在我的應用程序中,我使用來自BluetoothChat示例的類DeviceListActivity的稍微修改版本。該代碼工作以及所有我測試的設備上,但是當我發佈的應用程序,我開始收到這樣的報告:BluetoothChat中的StringOutOfBoundException示例
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的例子... 我希望有人可以解決這個問題或給我一個解釋,爲什麼發生這種情況... 謝謝...
編輯:該代碼已經檢查臨屋區t時的名稱存在和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);
}
你調試過,看看信息字符串是否是正確的大小?顯然你沒有從你的角度看到足夠多的角色。 – talnicolas 2012-04-11 19:58:23
當我在我的手機上測試它從未發生過,我從來沒有能夠重現錯誤... – Swordfish90 2012-04-11 20:19:30