How to properly close a cursor in android
If you use Kotlin (also available in Java in a bit different way), and Android 4.1 and above, you can use this:
cursor?.use {
//..do stuff
}
As an example, you can check here.
If you want to use Java, do something like:
try (Cursor cursor = ...) {
// do something
}
Closing cursor in finally
will guarantee it will be closed;
public void myfunc() {
Cursor c = null;
try {
c = ... // Open cursor here
return .... // maybe return something
} finally {
if(c != null) { c.close(); }
}
}
You're not closing cursor in getDateMove
, getTotalWeightLBS
, loadRooms
,...
Everywhere where cursor is not needed anymore close it. In those methods use try-finally, it will guarantee to execute code in finally block even when thrown exception occur.
Change code in your methods from this:
try{
// get data from cursor
} catch (Exception e) {
c.close();
}
to this:
try {
// get data from cursor
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
If an element is implementing AutoCloseable (like the Cursor.class
does), I would recommend to do a try-with-resources
, like described here.
If you use Retrolambda it has the try-with-resources
backported.
So your code:
Cursor cursor = db.query("tableName", columns, null, null, null, null, null);
try {
if (cursor.moveToFirst()) return cursor.getString(3);
else return null;
} finally {
cursor.close();
}
would simply turn into:
try (Cursor cursor = db.query("tableName", columns, null, null, null, null, null)) {
if (cursor.moveToFirst()) return cursor.getString(3);
else return null;
}