I have an Activity class which has an attribute that references an AsyncTask instance and this AsyncTask also has a reference to this Activity.
From the AsyncTask’s onPostExecute() I want to set the reference from the Activity to the AsyncTask to null (through the reference that has the AsyncTask instance to the Activity). Is it a good practice?
I am doing it at the last line of code of the method, because I am actually saying to the garbage collector that it can delete that instance as it is no longer referenced by any other object (the Activity). Is it correct, or am I wrong?
Edit: My answer below resumes the final solution I used.
Thanks!
Why do you need to keep the reference to the AsyncTask in the first place?
When is the reference no longer needed? What happens before the task has finished that requires you to hold a reference to the activity?
What I am saying is, you can start the async task without a reference to it so your problem goes away. But if for some reason you do need the reference, then by explaining your particular case more, we can suggest a better solution.
EDIT
Your main concern is not leaking the activity, not the other way around. If you really want to clean up all references properly, I would provide an attach/detach method on the async task so that activities can attach and detach themselves from the async task when nessecary and also provide a method on the activity that nullifies the async task refence and call that from your async task if an activity is still attached. Do not do it directly. The async task should not modify the activity directly. If possible even move the async task in a new file, don’t make it an internal class of the activity, that screams of leaks.