-1

I got this Error while using SQLite DATABASE.

07-16 17:45:13.106: E/AndroidRuntime(7703): Caused by: 
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

I'm Using SQLite Database to Store Book Objects in it.

public class MySQLiteHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "BookDB";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create book table
        String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT, "+
                "author TEXT )";

        // create books table
        db.execSQL(CREATE_BOOK_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older books table if existed
        db.execSQL("DROP TABLE IF EXISTS books");

        // create fresh books table
        this.onCreate(db);
    }
    //---------------------------------------------------------------------

    /**
     * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books
     */

    // Books table name
    private static final String TABLE_BOOKS = "books";

    // Books Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_AUTHOR = "author";

    private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};

    public void addBook(Book book){
        Log.d("addBook", book.toString());
        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, book.getTitle()); // get title
        values.put(KEY_AUTHOR, book.getAuthor()); // get author

        // 3. insert
        db.insert(TABLE_BOOKS, // table
                null, //nullColumnHack
                values); // key/value -> keys = column names/ values = column values

        // 4. close
        db.close();
    }

    public Book getBook(int id){

        // 1. get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        // 2. build query
        Cursor cursor =
                db.query(TABLE_BOOKS, // a. table
                COLUMNS, // b. column names
                " id = ?", // c. selections
                new String[] { String.valueOf(id) }, // d. selections args
                null, // e. group by
                null, // f. having
                null, // g. order by
                null); // h. limit

        // 3. if we got results get the first one
        if (cursor != null)
            cursor.moveToFirst();

        // 4. build book object
        Book book = new Book();
        book.setId(Integer.parseInt(cursor.getString(0)));
        book.setTitle(cursor.getString(1));
        book.setAuthor(cursor.getString(2));

        Log.d("getBook("+id+")", book.toString());

        // 5. return book
        return book;
    }

    // Get All Books
    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.setId(Integer.parseInt(cursor.getString(0)));
                book.setTitle(cursor.getString(1));
                book.setAuthor(cursor.getString(2));

                // Add book to books
                books.add(book);
            } while (cursor.moveToNext());
        }

        Log.d("getAllBooks()", books.toString());

        // return books
        return books;
    }

     // Updating single book
    public int updateBook(Book book) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put("title", book.getTitle()); // get title
        values.put("author", book.getAuthor()); // get author

        // 3. updating row
        int i = db.update(TABLE_BOOKS, //table
                values, // column/value
                KEY_ID+" = ?", // selections
                new String[] { String.valueOf(book.getId()) }); //selection args

        // 4. close
        db.close();

        return i;

    }

    // Deleting single book
    public void deleteBook(Book book) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. delete
        db.delete(TABLE_BOOKS,
                KEY_ID+" = ?",
                new String[] { String.valueOf(book.getId()) });

        // 3. close
        db.close();

        Log.d("deleteBook", book.toString());

    }
}
Squonk
  • 48,735
  • 19
  • 103
  • 135
Merciful
  • 109
  • 2
  • 2
  • 11
  • I think you are initializing cursors with the same name twice,close the first one and try running the program. – Natto Jul 16 '14 at 13:36

3 Answers3

3

You have to check if your Cursor has any line. Like this:

// 3. if we got results get the first one
    if (cursor.moveToFirst()){
       // do the work
}

cursor.moveToFirst() returns true if cursor is not empty, false otherwise.

You were trying to read from your Cursor when it was empty, hence the Exception.

EDIT: It is at your getBook(0), call getBook(1) instead, the first auto-incremented id value is 1, not 0. And change the Cursor check expression.

joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
  • @ffdzs It is different. Try it. See http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29 – joao2fast4u Jul 16 '14 at 13:38
  • Sorry, This web site banned us. Try another – Merciful Jul 16 '14 at 13:40
  • See the answer on http://stackoverflow.com/questions/12445010/what-is-the-use-of-movetofirst-in-sqlite-cursors – joao2fast4u Jul 16 '14 at 13:41
  • What do you mean banned?? – joao2fast4u Jul 16 '14 at 13:43
  • 403. That’s an error. Your client does not have permission to get URL /reference/android/database/Cursor.html from this server. (Client IP address: 151.***.46.165) We're sorry, but this service is not available in your country. – Merciful Jul 16 '14 at 13:44
  • And what about th second URL I gave you? – joao2fast4u Jul 16 '14 at 13:48
  • I can't understand! I should mentioned I used My class in main Like this: Book a; MySQLiteHelper db=new MySQLiteHelper(this); db.addBook(new Book("mard", "ishoon")); a=db.getBook(0); System.out.print(a); – Merciful Jul 16 '14 at 13:51
  • It is at your getBook(0), use getBook(1) instead, the first id value is 1. And change the cursor check expression. – joao2fast4u Jul 16 '14 at 13:55
  • If you like we could have more discussoin and know eachother!. if you want give an email address or messenger id! – Merciful Jul 16 '14 at 13:56
  • @ffdzs You are welcome. Please feel free to accept/upvote my answer. You have info about how to reach me in my profile. – joao2fast4u Jul 16 '14 at 14:00
  • I want to have Intimate relationship together! I can use your exprience and knowledge – Merciful Jul 16 '14 at 14:03
  • Here is Facebook Also Censored! – Merciful Jul 16 '14 at 14:05
  • I would invite you to chat if I could. You need 20 reputation for that. But you'll have my knowledge if I catch any other question from you :D – joao2fast4u Jul 16 '14 at 14:07
  • I'll benefit for me if we can communicate us! you from Portugal and I'm from Islamic Republic of Iran. Also this relationship can Improve my English skills! – Merciful Jul 16 '14 at 14:10
  • first auto-incremented id value is 1, not 0 - 100 likes for the information – Noor Hossain Oct 22 '20 at 23:28
0

try using

if(v != null && v.moveToFirst()) {
//your code
}

IT WORKED 4 ME

0

JUst try below code for single Condition you have to first check cursor is not null then after move to start position don't forgot to close it after work is done

Cursor cursor = db.query(...);if (cursor != null) {
if (cursor.moveToFirst()) {
    //do your stuff
}
cursor.close();

}

Now if you want check for multiple columns just replace while condition insted of if Thanks

Jayman Jani
  • 1,251
  • 10
  • 15