4

I have a large project with 100s of fragments. They all pretty much follow the pattern I am going to describe and my question will follow.

public class MyFragment extends Fragment implements View.OnClickListener {

    public void onDestroy(...) {
    }

    public void onCreateView(...) {
        ...
        root.findViewById(R.id.some_button).setOnClickListener(this);
        return root;
    }

    public void onClick(View v) { ... }
}

Do I need to free the listener from the fragment in onDestroy? Is this a memory leak or going to cause any problems at all? Is it considered good practice to clean these up? And if possible an explanation of why?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
J Blaz
  • 783
  • 1
  • 6
  • 26
  • 1
    Is there any observed perform hit currently? Why would a listener leak into additional memory? – OneCricketeer Jan 10 '17 at 23:16
  • No. I am mostly worried about future problems or back-grounded app problems. I have a partner who is telling me it is a good idea or good practice to release these listeners and I do not see a reason to. – J Blaz Jan 10 '17 at 23:33
  • 1
    I've never seen any references to removing click listeners. Any "fragment interaction listeners" that point to an Activity should be removed, sure, but only because the Activity is detached onDestroy. – OneCricketeer Jan 10 '17 at 23:35

1 Answers1

5

No, you don't have to release the onClickListener in the onDestroy event. Even though the fragment is the listener, the garbage collector is smart enough to resolve even circular references. As long as both are otherwise elligible for garbage collection, there won't be a problem.

NameSpace
  • 10,009
  • 3
  • 39
  • 40
  • Do you have any references or evidence to support this. Also, how do I know what is eligible for garbage collection? – J Blaz Jan 10 '17 at 23:46
  • You can read [this](http://stackoverflow.com/questions/1910194/how-does-java-garbage-collection-work-with-circular-references) about the statement on circular references, it's also backed up by personal experience using the memory profiler on android. – NameSpace Jan 10 '17 at 23:49
  • @JBlaz I would recommend the book `Thinking in Java`. Garbage collection process is very well explained there. – YTerle Jan 13 '18 at 11:42