1

好吧,这可能是一个愚蠢的问题,答案很简单,但是当使用记事本示例中的简单光标适配器时,我会从数据库中获取名称列表。

当我尝试通过将光标移动到行上并提取名称来“手动”执行此操作时,光标说返回零行......

这按照示例工作:

Cursor notesCursor = mDbHelper.fetchAllNotes();
    startManagingCursor(notesCursor);

    // Create an array to specify the fields we want to display in the list (only NAME)
    String[] from = new String[]{WeightsDatabase.KEY_NAME};

    // and an array of the fields we want to bind those fields to (in this case just text1)
    int[] to = new int[]{R.id.weightrows};

    // Now create a simple cursor adapter and set it to display
    SimpleCursorAdapter notes = 
            new SimpleCursorAdapter(this, R.layout.weights_row, notesCursor, from, to);
    setListAdapter(notes);

现在我正在尝试这样做,但它并不完全有效。简单的光标适配器是否在做一些我没有做的特别的事情?

//check # of rows, returns 0
    int mOne = notesCursor.getCount();
    //initial random string array
    String[] temp = new String[100];
    int i = 0;
    notesCursor.moveToFirst();
    do{

        temp[i]=notesCursor.getString(notesCursor.getColumnIndex(WeightsDatabase.KEY_ROWID)); //crashes here
        //index out of bounds
        i++;
    }while(notesCursor.moveToNext());

我已经让它工作了,但是返回一个特定的查询,比如返回所有名为“ _ ”的行。归还所有笔记有什么不同?

4

1 回答 1

0

moveToFirst()实际上返回 a boolean,因此您可以在尝试从 读取之前通过检查值来防止引发异常Cursor

if (notesCursor.moveToFirst()) {
    // do loop
}

至于为什么有 0 行,您是在尝试重新使用传递给 的相同游标SimpleCursorAdapter,还是独立失败的代码?如果您尝试重新使用它,我会Cursor在执行新的fetchAllNotes().

于 2011-02-19T00:46:59.893 回答