java - 为什么我必须在 onLoaderReset 中 swapCursor(null) ?

标签 java android garbage-collection android-loadermanager android-loader

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/

相关文章:

java - 通过netbeans启动android应用程序

java - 为什么在 ArrayList 中出现 ConcurrentModificationException?

android - 我可以通过 native java.net.Socket 连接 Android 客户端与使用 socket.io 的 Node js 服务器吗?

Android Espresso 问题 - 依赖冲突

Java 7 服务器默认 GC

java - OutOfMemoryError - 为什么等待线程不能被垃圾回收?

java - 解析字符串时遇到问题

java - 根据时间数组重新采样数据 - JAVA

java - Apache Poi 更新 xls 文件

garbage-collection - Go 使用什么样的垃圾收集器?