xorgx3
xorgx3

Reputation: 493

This field leaks a context object

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?

Upvotes: 31

Views: 25298

Answers (2)

Emanuel
Emanuel

Reputation: 8106

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.

That's why you should avoid assigning to Context relevant 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.

Upvotes: 19

Submersed
Submersed

Reputation: 8870

Use a WeakReference.

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

Upvotes: 27

Related Questions