Search code examples
androidcursor

Android cursor no step more than 1 record


My query return 198 registers but cursor only read one register. Why?

The mCount property of Cursor show 198.

This code:

    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 (my points not allow attach image here).


Solution

  • I think you're confusing while syntax.

    while (cursor.moveToNext());
    

    Will loop without doing anything until the Cursor is empty. I think you wanted a do/while as explained by CommonsWare answer.

    In my opinion, this is an unnecessary complicated way to do it. A lot of people don't know how to use Android Cursor. I've seen all kinds of complicated ways to do it (checking for null, moving to first, moving to index...), but this is the simplest way:

    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();
    }
    

    There's no need to check for null, Android Cursor API never returns a null cursor. You also need to close the Cursor once you've finished with it.