Android游标没有超过1条记录

时间:2015-04-11 21:10:24

标签: android cursor

我的查询返回198个寄存器但光标只读取一个寄存器。 为什么呢?

Cursor mCount 属性显示198。

此代码:

    public ArrayList<EnderecoOficina> retornarListaEnderecoOficina(String sCampo,
                                                               String sWhere) {
    ArrayList<EnderecoOficina> lista = new ArrayList<EnderecoOficina>();
    String query = String.format("SELECT %s FROM %s WHERE %s",
            sCampo,
            MyDBConstants.TABLE_OFICINAS,
            sWhere);

    SQLiteDatabase db = dbHandler.getReadableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    int i = 0;
    if (cursor != null && cursor.moveToFirst()){
        EnderecoOficina item = new EnderecoOficina(i++,
                cursor.getString(0),
                cursor.getString(1),
                cursor.getString(2));
        lista.add(item);
    } while (cursor.moveToNext());

    cursor.close();
    db.close();

    return  lista;
}

image link(我的观点不允许在此附加图片)。

1 个答案:

答案 0 :(得分:2)

我认为您会混淆while语法。

while (cursor.moveToNext());

Cursor为空之前,将不执行任何操作。我认为您需要{/ 3}}解释的do / while。

在我看来,这是一种不必要的复杂方法。很多人都不知道如何使用Android Cursor。我已经看过各种复杂的方法(检查null,转到第一个,转到索引......),但这是最简单的方法:

try {
    // Loop while there are records on the Cursor
    while (cursor.moveToNext()) {
       EnderecoOficina item = new EnderecoOficina(i++,
                cursor.getString(0),
                cursor.getString(1),
                cursor.getString(2));
        lista.add(item);
    }
} finally {
    // Make sure the cursor is closed no matter what
    cursor.close();
}

没有必要检查null,Android Cursor API永远不会返回空游标。完成后,您还需要关闭光标。

相关问题