0

我尝试实现以下代码

在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 上,我可以清楚地看到日志消息“inserting db”被打印了 3 次意味着数据日期真正添加到数据库中,但是日志消息“fetching db”打印了一次并给了我流动的错误说:

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

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

4

1 回答 1

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;


    }
于 2012-06-17T17:13:56.833 回答