2

In my attempt to abstract out common functionality for all the adapters in my application I come across something while looking through ArrayAdapter code that is bothering me.

From what I know the common pattern of using ListView is like follow:

  1. Create ListView in XML which will have a reference in Activity.
  2. Create an ArrayAdapter and give Activity as context to it.
  3. Set the ArrayAdapter in ListView.

A glance at code shows that ListView stores a strong reference to adapter and ArrayAdapter stores a strong reference to context i.e. my Activity. This creates a strong reference cycle and that is what bothering me a bit.

I know that this could be overcome by setting ListView reference to null in onDestroy. But this issues is never discussed in any tutorial while using the same technique that causes it.

My question is am I missing something here or it is common knowledge?

Abdullah
  • 7,143
  • 6
  • 25
  • 41
  • 1
    Java is not like objective-c or swift that using ARC, it does not have such issue I think. Read this: http://stackoverflow.com/questions/1910194/how-does-java-garbage-collection-work-with-circular-references – Surely May 02 '15 at 07:57
  • Practically everything UI related has a strong ref to context and most of the time its the activity. – Patrick May 02 '15 at 07:57

1 Answers1

2

ARC is not a real GC (Garbage Collector) that is being used by Java/Android, as such they have different behavior. One of such behavior is that for ARC it's up to the developer to break any circular references to prevent memory leak, but it's a non issue for Android, whose GC can detects such references automatically at runtime and dispose these objects appropriately.

It's always good to gain more insight on how a platform works under the hood, these info may help you differentiate the two and gain some understanding of GC:

Community
  • 1
  • 1
Kai
  • 15,284
  • 6
  • 51
  • 82