Memory leak in Fragment

from the CommonsWare Community archives

At April 23, 2020, 12:04pm, islam.farid2100 asked:

I would like to ask may onDetatch never called for un expected reason and thus parentView may cause memory leak. Is there a possibility for that.

open class TestFragment @ContentView constructor(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) {
private var parentView: BaseView? = null
    get() {
        if (field == null) {
            Timber.w("$this (test) is not attached to a BaseView host.")
        }

        return field
    }

override fun onAttach(context: Context) {
    super.onAttach(context)

    if (context is BaseView) {
        parentView = context
    } else {
        error("Fragment $this needs to get hosted by a BaseView")
    }
}

override fun onDetach() {
    parentView = null
    super.onDetach()
}

fun showLoading() {
    parentView?.showLoading()
}

}


At April 23, 2020, 12:45pm, mmurphy replied:

I have no idea if there are situations where onDetach() might not get called.

However, you will only have a memory leak if you are still holding onto your instance of TestFragment after such an occurrence.