我剛剛收到java.lang.IndexOutOfBoundsException:但無法理解它是由什麼引起的。基本上,我正在將sqlite表的記錄整合到listview中。 這是我的sql查詢從表中獲取記錄。如何解決IndexOutOfBoundsException:索引1無效,大小爲1?
public ArrayList<Integer> getRecordsCount(int no) {
ArrayList<Integer> count = new ArrayList<>();
Cursor c = database.rawQuery(
"select count(*) as TotalCount, tDate, " +
"strftime('%d', tDate) as DayPart, " +
"strftime('%m', tDate) as MonthPart, " +
"strftime('%Y', tDate) as YearPart " +
"from library " +
"where type = '" + no + "' " +
"group by MonthPart, YearPart", null);
while (c.moveToNext()) {
count.add(c.getInt(0));
}
return count;
}
這是我的方法檢索數據: -
public void setDataInList(int no) {
if (no == 0) {
ArrayList<Integer> count = helper.getRecordsCount(1);
mainGetLibraryModels.clear();
MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no);
for (int i = 0; i < modelWS.getRecords().size(); i++) {
WSLibraryModel model = new WSLibraryModel();
model.setAmount(modelWS.getRecords().get(i).getAmount());
model.setTotalCount("" + count.get(i));
model.setYearPart(modelWS.getRecords().get(i).getYearPart());
model.setMonthPart(modelWS.getRecords().get(i).getMonthPart());
mainGetLibraryModels.add(model);
}
adapter.notifyDataSetChanged();
} else if (no == 1) {
ArrayList<Integer> count = helper.getRecordsCount(2);
mainGetLibraryModels.clear();
MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no);
for (int i = 0; i < modelWS.getRecords().size(); i++) {
WSLibraryModel model = new WSLibraryModel();
model.setAmount(modelWS.getRecords().get(i).getAmount());
model.setTotalCount("" + count.get(i));
model.setYearPart(modelWS.getRecords().get(i).getYearPart());
model.setMonthPart(modelWS.getRecords().get(i).getMonthPart());
mainGetLibraryModels.add(model);
}
adapter.notifyDataSetChanged();
} else {
mainGetLibraryModels.clear();
MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no);
for (int i = 0; i < modelWS.getRecords().size(); i++) {
WSLibraryModel model = new WSLibraryModel();
model.setAmount(modelWS.getRecords().get(i).getAmount());
model.setTotalCount(" - ");
model.setYearPart(modelWS.getRecords().get(i).getYearPart());
model.setMonthPart(modelWS.getRecords().get(i).getMonthPart());
mainGetLibraryModels.add(model);
}
adapter.notifyDataSetChanged();
}
}
但是,當我運行這段代碼,它給了我這個錯誤?
FATAL EXCEPTION: main Process: com.teezom, PID: 14168
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)
因爲count數組的大小爲1,所以你需要通過0索引來訪問 – ThiepLV