我试图通过ID获取行中的所有元素时得到一个空光标

时间:2015-05-13 07:47:01

标签: android sqlite cursor

我试图通过ID使用游标获取sqlite中行的所有元素。光标不为空,但我似乎无法使用光标操作,这是我的代码:

    public Book getBookByid (int itemId) {

            String selectQuery = "SELECT * FROM " + tables[0] + " WHERE " + SQLiteHelper.ITEM_ID + " = " + itemId;
            Cursor cursor = database.rawQuery(selectQuery, null);

            Book bookRead = new Book();
            if(cursor!=null) {
                Log.i("myApp","cursor not null");
                if (cursor.moveToFirst()) {
                    Log.i("myApp","title" + cursor.getColumnIndex(arrayFields.get(0)[1]));
                    bookRead.setTitle(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[1])));
                    bookRead.setGenre(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[2])));
                    bookRead.setDescription(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[3])));
                    bookRead.setRecommendation(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[4])));
                    bookRead.setPhoto(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[5])));
                    bookRead.setLike(cursor.getInt(cursor.getColumnIndex(arrayFields.get(0)[6])));
                }
                Log.i("myApp","title" + bookRead.getTitle());
       }
       cursor.close();
     return bookRead;
}

问题是代码没有输入if(cursor.moveToFirst())所以我无法将值赋给我的对象,获得空对象引用。

我的日志显示以下内容:

05-13 09:37:23.720  13918-13918/com.appforbrands.meloapunto I/myApp﹕ cursor not null
05-13 09:37:23.720  13918-13918/com.appforbrands.meloapunto I/myApp﹕ titlenull

我在logcat中也收到蓝色警告或错误:

05-13 10:04:14.555    3969-3969/com.appforbrands.meloapunto W/Bundle﹕ Key itemId expected Integer but value was a java.lang.Long.  The default value 0 was returned.
05-13 10:04:14.559    3969-3969/com.appforbrands.meloapunto W/Bundle﹕ Attempt to cast generated internal exception:

2 个答案:

答案 0 :(得分:1)

这是调试功能所需的步骤:

  1. 确保您拥有有效的数据库连接。
  2. 检查并确保您的原始查询正确无误。
  3. 您的数据中存在itemID。

答案 1 :(得分:0)

Sqlite可能会在您的Sqlite书籍表中发现您的ID时感到困惑,因此查询无法找到任何行。检查表定义或在查询字符串中手动编写表id。