【问题标题】:android's Sqlite cursorandroid Sqlite 光标
【发布时间】:2016-03-02 21:25:17
【问题描述】:

当我构建 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();
            }
        });

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

最后,我将add_data的顺序交换为“作者”和“名称”,它运行

有什么问题吗?谢谢!

【问题讨论】:

    标签: android sqlite cursor


    【解决方案1】:

    如果您希望在完成时保存值,您需要处于事务中(并提交它)。

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

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

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

    【讨论】:

      【解决方案2】:

      试试这个
      用于读取数据使用

      this.getReadableDatabase() 
      

      你正在使用

      getWritableDatabase()
      

      在 query_data.setOnClickListener 中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 2018-09-13
        • 2020-03-14
        • 1970-01-01
        • 2017-09-08
        • 1970-01-01
        相关资源
        最近更新 更多