Gonzalo GM
Gonzalo GM

Reputation: 99

Cursor does not work listview

I have this method to populate a listview

private void llenarLista() {
    SQLiteDatabase bd= SQLiteDatabase.openDatabase(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SuperStock/SuperStock.db", null, 0);
    Cursor cursor = bd.rawQuery("select _id, cod_cliente, nom_cliente, fecha, estado_envio,estado, total_final from pedidos where estado_envio='pendiente' ORDER BY fecha DESC", null);
    if(cursor.moveToFirst()) {
        adaptador = new AdaptadorListaPedidos(ConsultarPedidos2.this, cursor);
        lista.setAdapter(adaptador);
    }
    else
        mensaje("Linea 66","cursor vacio");

    cursor.close();
    bd.close();
}

but I have problems with the cursor, when you run cursor.close () the list is empty, and when commented that //cursor.close line (), the list is displayed populated. I'm misusing the cursor? Can anyone help with this?

Upvotes: 0

Views: 36

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006594

You cannot close() a Cursor while it is in use by a CursorAdapter. Please:

  • Open your database once, on a background thread

  • Run your query on a background thread, perhaps the same thread that opened your database

  • Close the cursor when you are done with the CursorAdapter, such as in onDestroy() of the activity or fragment that is hosting the ListView

  • Close the database, if practical, when you are done with the database (which, by definition, is sometime after you are done with the Cursor that you got from the database)

Upvotes: 1

Related Questions