john john - 1 month ago 16
Android Question

Index out of bounds in android

I am trying to read the data from api, populate that in DB and show it in the list view. I keep on getting the out of index bound but i am not sure why. Book is the simple book class with sting phoneNo and string name. I am able to retrieve the data. i get the right output when i print the data that i fetch but i keep on getting into issues when i try to insert the data in database and fetch it.

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;
}

Answer

You are specifying there are four items you will be iterating through:

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 means that you are trying to retrieve an item from the list by an index greater than the maximum index in the list. Instead you can try finding out the number of items in the list:

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

or by just iterating through the list itself:

for(Book book: list)
Comments