2012-04-11 22 views
0

在我的應用程序中,我使用來自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); 
} 
+0

你調試過,看看信息字符串是否是正確的大小?顯然你沒有從你的角度看到足夠多的角色。 – talnicolas 2012-04-11 19:58:23

+0

當我在我的手機上測試它從未發生過,我從來沒有能夠重現錯誤... – Swordfish90 2012-04-11 20:19:30

回答

0

好像你info.length()少比尺寸。確保子串方法不會得到任何負值(s)作爲參數。將代碼的關鍵部分放在try/catch塊中以避免出現異常。

+0

是的,但有趣的是,它不能...因爲它是設備名稱+ MAC地址(17個字符長)。所以我想不出爲什麼它更短 – Swordfish90 2012-04-11 20:18:27

+0

好吧,但想象一下,如果mac可用,但名稱是空的字符串或反之亦然,那麼它的問題,儀式? – waqaslam 2012-04-11 20:31:16

+0

謝謝你的幫助,但這項檢查已經實施,但這並沒有阻止例外...... :( – Swordfish90 2012-04-11 20:45:45