Android 的文档 ( https://developer.android.com/guide/components/loaders.html ) 说,当我使用加载器执行 SQL 查询时,我 应该在 onLoaderReset 方法中执行 swapCursor(null) :
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);
}
我不明白为什么要在 onLoaderReset 中将适配器的光标交换为 null。据我所知,当 Activity 被破坏时,加载程序会被重置。但当 Activity 被破坏时, 它符合垃圾回收条件,并且此 Activity 保留的所有引用也符合垃圾回收条件。所以这些适配器是否存在并不重要 保留对游标的 e 引用 - 它不会阻止游标被垃圾收集。
那么,为什么我应该在 onLoaderReset 中将适配器的光标交换为 null?
最佳答案
如果 Activity 的底层成员引用 Activity 外部,则 Activity 不会被垃圾回收。当它的所有成员将来都可能不再使用时,它将被垃圾收集。
if swapCursor(null);
将删除光标的所有底层引用。否则它将创建一个 memory leak并且您的 Activity 不会被垃圾收集。
关于java - 为什么我必须在 onLoaderReset 中 swapCursor(null) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666215/