2

I was reading this documentation on the SupportMapFragmet, and it says:

Any objects obtained from the GoogleMap is associated with the view. It's important to not hold on to objects (e.g. Marker) beyond the view's life. Otherwise it will cause a memory leak as the view cannot be released.

I am a little puzzled about this because there isn't a way to modify the Markers unless you hold a reference of them, like many questions in here say (like this and this)... so is it there something that I am missing?

I am currently using a HashMap to associate my Markers with other Objects and I can't see how to avoid it. Will this leak memmory? Is it there a recommended way to edit the Markers and avoid memmory leak?

Community
  • 1
  • 1
Michel Feinstein
  • 13,416
  • 16
  • 91
  • 173

2 Answers2

2

It is very likely that the marker has a reference to the map, the same way drawables hold internal references to views to which they are bound. As long as you hold the marker, you are probably also holding a reference vicariously to the map.

I don't know why they wouldn't use a weak reference. But if they did they wouldn't feel the need to warn you about leaking from holding on to a marker. As such, if your hashmap outlives the fragment/activity hosting the map, it will likely be a memory leak.

NameSpace
  • 10,009
  • 3
  • 39
  • 40
  • So the recommended way is to assure all the markers are released when the map is released? I guess this will be related to `onCreateView` and `onDestroyView`, but still, I can't say I feel 100% safe on this... – Michel Feinstein Aug 08 '14 at 16:19
  • aye, hold them in a collection that will get destroyed whenever the map gets destroyed. A non-static collection in the hosting frag or activity. If you destroy the map before the host (e.g. detaching it, or replacing with a new map), just .clear() the collection. – NameSpace Aug 08 '14 at 23:57
  • Well, I guess the trick is to destroy the collection BEFORE the map is destroyed...and this will be related to when the Garbage Collector does it cleaning, which might lead to unpredictable behavior...or am I missing something? – Michel Feinstein Aug 11 '14 at 00:19
  • The garbage collector will get it eventually after you destroy the last reference. Also, it often takes the garbage collector several passes to get rid of circular references, finalizers, etc that may keep an object alive. – NameSpace Aug 11 '14 at 01:44
  • Ok...understood! I will leave this question open, sometimes some folks from google appear in here, this might trigger an official response... – Michel Feinstein Aug 11 '14 at 15:38
2

After following the above advice and removing all markers from the map before the fragment was destroyed, I was still getting a memory leak. The solution for me ended up being calling clearTileCache on my custom TileOverlay before the Fragment was destroyed.

Bobby
  • 6,840
  • 1
  • 22
  • 25