Android's documentation ( https://developer.android.com/guide/components/loaders.html ) says that when I use loaders to do SQL queries, I should do swapCursor(null) in onLoaderReset method:
onLoaderReset This method is called when a previously created loader is being reset, thus making its data unavailable. This callback lets you find out when the data is about to be released so you can remove your reference to it.
This implementation calls swapCursor() with a value of null:
// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
...
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
I don't understand why should I swap adapter's cursor to null in onLoaderReset. As far as I know, loader is reset when activity is destroyed. But when activity is destroyed, it is eligible for garbage collection and all references that this activity keeps are also eligible for garbage collection. So it doesn't matter if any of those adapters keeps e reference to a cursor - it won't prevent the cursor from being garbage collected.
So, why should I swap adapter's cursor to null in onLoaderReset?
Activities will not be garbage collected if its underlying members are referencing out side of the activity. It will be garbage collected when all its members are may not be used in the future.
if
swapCursor(null);
will remove all the underlying references with the cursor. otherwise it will create a memory leak and your activity will not get garbage collected.