Search code examples
androidsqlitecursor

android's Sqlite cursor


when i build a SQLiteDatabase

public static final String CREATE_BOOK = "create table Book(" + "id integer primary key autoincrement," + "author text," + "price real," + "pages integer," + "name text," + "category_id integer)";

then there is a button add_data

add_data.setOnClickListener(new View.OnClickListener() {
     @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbhelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("author", "jose");
                values.put("name", "Thank you!");
                values.put("pages", 999);
                values.put("price", 99.9);
                db.insert("Book", null, values);    }
        });

and i want to query the table

query_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbhelper.getWritableDatabase();
                Cursor cursor = db.query("Book", null, null, null, null, null, null);
                if(cursor.moveToFirst()){
                    do {
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        String author = cursor.getString(cursor.getColumnIndex("author"));
                        int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                        double price = cursor.getDouble(cursor.getColumnIndex("price"));
                        Log.d("MainActivity", "book name is" + name);
                        Log.d("MainActivity", "book author is" + author);
                        Log.d("MainActivity", "book pages is" + pages);
                        Log.d("MainActivity", "book prices is" + price);
                    }while (cursor.moveToNext());
                }
                cursor.close();
            }
        });

And i run it, there is some wrong: Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 5 columns. Make sure the Cursor is initialized correctly before accessing data from it.

At the end, i swap the order of the add_data as "author" and "name", it run

what's problem of it?Thank you!


Solution

  • You need to be in a transaction (and COMMIT it) if you want the values to be saved on completion.

    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction()
    

    ...insert, update, delete, etc

    if (ok) {
      db.setTransactionSucessful();
    }
    db.endTransaction();
    db.close();