android – This field leaks a context object-ThrowExceptions

Exception or error:

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?

How to solve:

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.

###

Use a WeakReference.

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

Leave a Reply

Your email address will not be published. Required fields are marked *