光标索引超出范围"索引0请求:大小为0"错误

时间:2014-04-16 10:39:10

标签: android android-sqlite

我运行项目时遇到此异常, 这是主要活动的一部分

  private void fillData() {
    // Get all of the notes from the database and create the item list
    Cursor notesCursor = mDbHelper.fetchAllNotes();

    if (notesCursor != null) {
        notesCursor.moveToFirst();
        do {
            messagesList.add(notesCursor.getString(notesCursor
                    .getColumnIndex(DbAdapter.KEY_FIELD2)));
            Log.e("Test", notesCursor.getString(notesCursor
                    .getColumnIndex(DbAdapter.KEY_FIELD2)));

        } while (notesCursor.moveToNext());
    }
    customAdapter.notifyDataSetChanged();
    // setListAdapter(notes);
}

2 个答案:

答案 0 :(得分:0)

首先,您应该测试notesCursor!= null AND notesCursor.moveToNext()(返回一个布尔值)。游标不为null并不意味着它有结果。而且,你使用do / while循环,这意味着你假设你总是得到一个结果......

我会说你应该用它来代替:

private void fillData() {
    // Get all of the notes from the database and create the item list
    Cursor notesCursor = mDbHelper.fetchAllNotes();

    if (notesCursor != null) {
        while(notesCursor.moveToNext())
        {
            messagesList.add(notesCursor.getString(notesCursor
                    .getColumnIndex(DbAdapter.KEY_FIELD2)));
            Log.e("Test", notesCursor.getString(notesCursor
                    .getColumnIndex(DbAdapter.KEY_FIELD2)));
        }
        customAdapter.notifyDataSetChanged();
    }
}

我还认为如果进行了一些修改,你应该只调用notifyDataSetChanged():所以将它移到你的if子句中:如果没有改变,你不必要求你的系统重新计算你的ListView ......

通常,调用moveToNext时可能会出现错误:您的光标没有任何结果,但您要求它移动到下一个...下一步是什么?如果没有结果,就无法移动到下一个......

答案 1 :(得分:0)

SQliteDatabase.query()返回一个Cursor对象,该对象位于第一个条目之前。 游标永远不会为null但它可以为空。您的query()将返回Cursor对象,否则将引发异常。它永远不会返回null。

boolean moveToFirst():
如果cursor为空,

返回false,否则它会将光标移动到结果的第一行并返回true。

您可以查看以下内容:

notesCursor.moveToFirst();

while(notesCursor.moveToNext())
        {
            messagesList.add(notesCursor.getString(notesCursor
                    .getColumnIndex(DbAdapter.KEY_FIELD2)));
            Log.e("Test", notesCursor.getString(notesCursor
                    .getColumnIndex(DbAdapter.KEY_FIELD2)));
        }
        customAdapter.notifyDataSetChanged();
    }
相关问题