Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This field leaks a context object

Tags:

android

kotlin

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?

like image 775
xorgx3 Avatar asked Oct 17 '17 19:10

xorgx3


2 Answers

Use a WeakReference.

val textRef: WeakReference<TextView> = WeakReference(debtorText)
like image 91
Submersed Avatar answered Oct 19 '22 02:10

Submersed


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.

like image 18
Emanuel S Avatar answered Oct 19 '22 02:10

Emanuel S