Search code examples
androidandroid-contentproviderandroid-cursorandroid-intentservice

Should I close the cursor when exiting IntentService?


I'm pretty sure the cursor is destroyed with the IntentService instance, but I just want to be sure there's no memory leak. And if it's a normal practice. I'm querying my custom ContentProvider.

class MyService extends IntentService {
    protected void onHandleIntent(Intent intent) {
        Cursor cursor = getContentResolver().query(
                MyContentProvider.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() == 0) {
            return; // exit the method
        } else {
            cursor.close();
        }
        // some code...
    }
}

Solution

  • Every time you work with a cursor, you should wrap it in try - finally and close it:

    Cursor cursor = …;
    if (cursor == null)
        return;
    try {
        …
    } finally {
        cursor.close();
    }
    

    This will ensure no memory leaks will occur even when an exception is thrown.

    Java 7 brings try-with-resources but only Android API 19+ supports it:

    try (Cursor cursor = …)
    {
        …
    } // Cursor closed automatically