Benefits of closing a cursor

2

I have an application in which I use Cursors to save the data obtained from a SQLite query and in many occasions I forget to close them Cursor.close();

What problems can that bring me? Does it consume more RAM in the device?

If that were the case, it would make up for me to go through the whole app and close them all, but if it does not have benefits, I will not hurry to close them.

    
asked by borjis 13.10.2016 в 18:21
source

2 answers

0

Imagine an application where you require several DAO operations to read data, if these cursors are not closed the data would remain in memory.

    public List<Articulo> obtenerArticulos() {
    ...
    ...
    Cursor cursor = db.query(Articulos.TABLE_NAME, null, null, null, null,  null, Articulos.POSICION + DESC);
    while (cursor.moveToNext()) {
            ...
            articulos.add(articulo);
        }
        cursor.close(); // * Importante cerrar el cursor creado por cada operación!.
        return articulos;
    }

The documentation tells you about the method close ()

  

Close the cursor, freeing all resources and making the instance   invalidates.

Closing the cursor frees resources, I think it is the most important benefit which answers your question.

    
answered by 13.10.2016 / 20:26
source
0

I have always read that it is highly recommended to close them since it can cause a memory leak in your application (leak memory).

Although it depends on the method you are using to generate your cursor. If you use the method managedQuery (deprecated in API 11) you will not need to use it since it closes it automatically. As indicated by the Android documentation:

  

Warning : Do not call close () on a cursor obtained using this method, because the activity will do that for you at the appropriate time. However, if you call stopManagingCursor (Cursor) on a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call close ().

which is to say that this method will close the cursor at the appropriate time and that in case you use the stopManagingCursor(Cursor) method (also deprecated in API 11) if you need to close it.

As recommended by the Android documentation, use CursorLoader as a replacement (in case that you are using any of the above methods).

    
answered by 13.10.2016 в 19:45