CursorIndexOutOfBounds error when changing views
07-05 23:23:27.497: ERROR/AndroidRuntime(390): java.lang.RuntimeException: Unable to resume activity {com.fttech.books/com.fttech.books.creatBook}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-05 23:23:27.497: ERROR/AndroidRuntime(390): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
I keep getting these errors when i run i change views and it calls my onResume method to re-populate EditText fields. Here is my code for on resume:
protected void onResume(){
Log.v(tag, "In onResume!");
Cursor it = mDbHelper.fetchBook(mRowId);
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
if (it.moveToFirst()) {
populateFields();
}
Here is my setRowIdFromIntent method:
private void setRowIdFromIntent(){
if(mRowId == null){
Bundle extras = getIntent().getExtras();
mRowId = extras != null
? extras.getLong(DbAdapter.KEY_ROWID)
:null;
}
PopulateFields method which retrieves information from the database if the activity is paused and then resumed, such as when i change from porttrait to landscape.
private void populateFields() {
if(mRowId != null){
Cursor books = mDbHelper.fetchBook(mRowId);
开发者_开发技巧 startManagingCursor(books);
bookTitle.setText(books.getString(books.getColumnIndexOrThrow(DbAdapter.KEY_BOOK)));
bookAuthor.setText(books.getString(books.getColumnIndexOrThrow(DbAdapter.KEY_AUTHOR)));
bookIsbn.setText(books.getString(books.getColumnIndexOrThrow(DbAdapter.KEY_ISBN)));
ratingBar.setRating(books.getFloat(books.getColumnIndex(DbAdapter.KEY_RATING)));
Use the moveToFirst()
method of the cursor. Your code should be something like:
if (cursor.moveToFirst()) {
\\ populate fields
} else {
\\ not found!
}
Also make sure that your query returns the columns you are trying to fetch.
I have written a ORM framework for that. https://github.com/ahmetalpbalkan/orman
You can easily write Android applications using SQLite with that. It uses your Java classes (you can create Book
class in this case) as database tables (entities).
If you use this framework, you won't see cursors at all. All you'll see is going to be:
List<Book> books = Model.fetchAll(Book.class);
then you'll have a list of all books in the database. You won't see column mappings, database and table generation at all. Very useful in your case.
精彩评论