使用sqlite数据库索引超出绑定的异常

时间:2012-06-17 16:54:11

标签: android sqlite

我尝试实现以下代码

在activity.java文件中

      DatabaseEvent mDbHelper = new DatabaseEvent(getApplicationContext());
      mDbHelper.open();
      Cursor notesCursor = mDbHelper.fetchEvent();
             startManagingCursor(notesCursor);
        String[] from = new String[]{DatabaseEvent.KEY_ETITLE, DatabaseEvent.KEY_DISTANCE, DatabaseEvent.KEY_IMGNAME, DatabaseEvent.KEY_DESCRIPTION, DatabaseEvent.KEY_EID};
            int[] to = new int[]{R.id.title, R.id.duration, R.id.list_image, R.id.artist, R.id.id};
            SimpleCursorAdapter event = 
                    new SimpleCursorAdapter(getApplicationContext(), R.layout.list_row, notesCursor, from, to);

在DatabaseEvent.java中

               public long createEvent(String title, String distance, String imgname, String description, String eid) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ETITLE, title);
        initialValues.put(KEY_DISTANCE, distance);
        initialValues.put(KEY_IMGNAME, imgname);
        initialValues.put(KEY_DESCRIPTION, description);
        initialValues.put(KEY_EID, eid);

          Log.v("INFO1","inserting db");
        return mDb.insert(EVENT_TABLE, null, initialValues);

    }


         public Cursor fetchEvent() {
         Log.v("INFO1","fetching db");
         Cursor mCursor = mDb.query(EVENT_TABLE, new String[] {KEY_ROWID, KEY_ETITLE, KEY_DISTANCE,
                KEY_IMGNAME, KEY_DESCRIPTION, KEY_EID}, null, null,null,null, KEY_DISTANCE+" ASC");

        return mCursor;


    }

在logcat上,我可以清楚地看到日志消息“插入数据库”被打印三次意味着数据日期确实被添加到数据库中,但是日志消息“获取数据库”打印一次并给我流动的错误说:

             CursorIndexOutOfBoundException index -1, requsted, with a size of 60,

我尝试了不同的功能,如moveToFirst()和moveToNext(),但仍然无法解决问题,任何人都可以帮助我,任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:2)

您忘了加入mCursor.moveToFirst();

将您的代码更改为

   public Cursor fetchEvent() {
         Log.v("INFO1","fetching db");
         Cursor mCursor = mDb.query(EVENT_TABLE, new String[] {KEY_ROWID, KEY_ETITLE, KEY_DISTANCE,
                KEY_IMGNAME, KEY_DESCRIPTION, KEY_EID}, null, null,null,null, KEY_DISTANCE+" ASC");
        mCursor.moveToFirst();
        return mCursor;


    }