我正在尝试从api中读取数据,在数据库中填充该数据并在列表视图中显示它。我继续超出索引限制,但我不知道为什么。 Book是带有sting phoneNo和字符串名称的简单书类。我能够检索数据。当我打印我获取的数据时,我得到正确的输出,但当我尝试在数据库中插入数据并获取它时,我仍然遇到问题。
List<Book> list = db.getAllBooks();
for(int i = 0; i<4; i++) {
thatName[i] = list.get(i).getName();
thatMobile[i] = list.get(i).getPhoneNo();
Log.d("List 1", thatName[i]);
Log.d("List 2", thatMobile[i]);
}
customListViewAdapter = new CustomListViewAdapter(getApplication(),thatName,thatMobile);
listView.setAdapter(customListViewAdapter);
};
}
DB
public List<Book> getAllBooks() {
List<Book> books = new LinkedList<Book>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_BOOKS;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build book and add it to list
Book book = null;
if (cursor.moveToFirst()) {
do {
book = new Book();
book.setPhoneNo(cursor.getString(1));
book.setName(cursor.getString(0));
//book.setAuthor(cursor.getString(2));
// Add book to books
books.add(book);
} while (cursor.moveToNext());
}
Log.d("getAllBooks()", books.toString());
// return books
return books;
}
答案 0 :(得分:1)
您正在指定您将迭代的四个项目:
for(int i = 0; i<4; i++) {
thatName[i] = list.get(i).getName();
thatMobile[i] = list.get(i).getPhoneNo();
Log.d("List 1", thatName[i]);
Log.d("List 2", thatMobile[i]);
}
IndexOutOfBoundsException
表示您尝试通过大于列表中最大索引的索引从列表中检索项目。相反,您可以尝试找出列表中的项目数:
for(int i = 0; i < list.size(); i++)
或只是遍历列表本身:
for(Book book: list)