This field leaks a context object

2019-04-19 02:16发布

问题:

My code:

class HttpRequestTask(private val debtWsUrl : URI, debtorText : TextView) : 
      AsyncTask<Void, Void, Iterable<Debtor>?>() {
            val debtorText: TextView = debtorText
}

Why line with TextView shows warning:

This field leaks a context object

?

How can I prevent this?

回答1:

You assign a View to your HttpRequestTask. Since a View requires a Context you are leaking it.

Just think what happen if the View has been destroyed but the Http Task is not finished yet.

Thats why you should avoid assigning Context relevanted stuff inside methods which may give something back while the view has been already killed.

Remove the debtorText and return the value to set it inside your view.



回答2:

Use a WeakReference.

val textRef: WeakReference<TextView> = WeakReference(debtorText)