ArrayList错误IndexOutOfBounds异常

时间:2013-09-01 14:28:14

标签: android loops arraylist

我正在使用ArrayList来遍历应用程序的联系人列表,并将SMS发送到我使用了以下数字的这些号码:

ArrayList<String> contacts = new ArrayList();
                        List<String> list = SM.getAllValue();
                            for(String string : list){
sb.append(string.toString());
                                contacts.add(string);
                                }
                            for(int i = 0; i <= contacts.size(); i++){
                                String numberToSend = contacts.get(i).toString();
                                sendSMS(numberToSend, sms);
                            }

代码SM.getAllValues()会在List(s)中返回所有用户的联系首选项。程序工作 - 消息被发送但应用程序每次都崩溃,在logcat中给出以下内容:

09-01 20:02:44.852: E/AndroidRuntime(19151): FATAL EXCEPTION: main
09-01 20:02:44.852: E/AndroidRuntime(19151): java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
09-01 20:02:44.852: E/AndroidRuntime(19151):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at java.util.ArrayList.get(ArrayList.java:311)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at com.vaw.selfhelp.SmsActivity$4.onClick(SmsActivity.java:163)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at android.view.View.performClick(View.java:2485)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at android.view.View$PerformClick.run(View.java:9080)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at android.os.Handler.handleCallback(Handler.java:587)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at android.os.Looper.loop(Looper.java:130)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at android.app.ActivityThread.main(ActivityThread.java:3687)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at java.lang.reflect.Method.invokeNative(Native Method)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at java.lang.reflect.Method.invoke(Method.java:507)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
09-01 20:02:44.852: E/AndroidRuntime(19151):    at dalvik.system.NativeStart.main(Native Method)

第163行:

String numberToSend = contacts.get(i).toString();

请帮助:)

1 个答案:

答案 0 :(得分:1)

更改

for(int i = 0; i <= contacts.size(); i++){

for(int i = 0; i < contacts.size(); i++){