android的Sqlite游标

时间:2016-03-02 13:13:55

标签: android sqlite cursor

当我构建一个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)";

然后有一个按钮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);    }
        });

我想查询表

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

我运行它,有一些错误:无法从CursorWindow读取第0行,第1列,其中包含1行,5列。在从中访问数据之前,请确保Cursor已正确初始化。

最后,我将add_data的顺序换成" author"和"名称",它运行

它的问题是什么?谢谢!

2 个答案:

答案 0 :(得分:0)

如果您希望在完成时保存值,则需要处于事务(并且COMMIT)。

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

...插入,更新,删除等

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

答案 1 :(得分:0)

试试这个
要阅读数据,请使用

this.getReadableDatabase() 

您正在使用

getWritableDatabase()

在query_data.setOnClickListener