Search code examples
androidmemory-leakscursor

where to close the cursor?


i have a cursor that I am using in the following code. But I want to close the cursor after it is used and no longer needed. The problem is that the cursor is used in the return statement, but I can't close it after the return statement because that is unreachable code. It is used in the return statement so I can't close it above that line. How do I close the cursor? This is not like the old managedQuery, I assume that you have to close it.

   public String getPath(Uri uri) {
    String[] projection = { MediaStore.Audio.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
      // cursor.close() <--- not possible because it is unreachable code after return
}

Solution

  • You can assign it to a String object then close cursor and return it.

    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;