我已经声明了这个多维ArrayList:
public class Rete {
public RequestQueue requestQueue;
public ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
public Rete(RequestQueue requestQueue) {
this.requestQueue = requestQueue;
result.add(new ArrayList<String>(4));
}
}
我想要添加这样的数据:
for (int i = 0; i < utenti.length(); i++) {
JSONObject student = utenti.getJSONObject(i);
result.get(i).add(student.getString("nome"));
result.get(i).add(student.getString("cognome"));
result.get(i).add(student.getString("numero"));
result.get(i).add(student.getString("email"));
}
但应用程序崩溃... logcat:
10-11 20:10:27.048 6429-6429/com.rete.prova.ale.reteale E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rete.prova.ale.reteale, PID: 6429
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.rete.prova.ale.reteale.Rete$4.onResponse(Rete.java:101)
at com.rete.prova.ale.reteale.Rete$4.onResponse(Rete.java:89)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
问题是ArrayList ..如何以正确的方式对它们进行初始化?
答案 0 :(得分:3)
这是你的arraylist
public ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
这就是你出错的地方
result.get(i).add(student.getString("nome"));
result.get(i).add(student.getString("cognome"));
result.get(i).add(student.getString("numero"));
result.get(i).add(student.getString("email"));
您正在获取 IndexOutOfBoundsException ,因为您正在尝试从空数组中获取对象。
试试这个
ArrayList<String> studentdata = new ArrayList<String>();
studentdata.add(student.getString("nome"));
studentdata.add(student.getString("cognome"));
studentdata.add(student.getString("numero"));
studentdata.add(student.getString("email"));
result.add(studentdata);
答案 1 :(得分:1)
在for循环的每次迭代中,您需要实例化一个新的<root>
并将其添加到ArrayList
result
并摆脱
for (int i = 0; i < utenti.length(); i++) {
JSONObject student = utenti.getJSONObject(i);
ArrayList<String> tmp = new ArrayList<>(4);
tmp.add(student.getString("nome"));
tmp.add(student.getString("cognome"));
tmp.add(student.getString("numero"));
tmp.add(student.getString("email"));
result.add(tmp);
}