Search code examples
androidkotlinmemory-leaksandroid-contextgroupie

Memory leaks when using static context items in android


So I have a class with static UI elements like so:

class MyClass {
    companion object {
        lateinit var item:ChannelItem
    }
}
// Item from groupie
class ChannelItem(var channel:Channel): Item<ViewHolder>() {
    // bind
    // getLayout
}

This seems to cause a memory leak, is there a quick way to fix it without changing the code too much?

I'm thinking about replacing the item with

var map = mutableMapOf<String, ChannelItem?>()

would this fix the memory leak? and if so why?

Thanks a lot


Solution

  • Static UI elements make no sense in Android First off, UI objects are bound to a specific Activity. They can't be used from other activities or displayed outside of their Activity. So making them static doesn't bring value

    Secondly, this will always be a memory leak. Each view has a reference to its Activity. Putting an Activity in a static variable means it can't be garbage collected, because there's a valid reference to it. That will basically cause every variable in that Activity to leak. Including the UI elements, which tend to be memory hungry (each image takes 4 bytes per pixel).

    You need to rethink what you're trying to do with this code. I actually can't tell. If you made them static so you can change them from other activities- don't do that. Make them based off a model object, and alter the data in the model instead. Let the UI reinitialize itself based off the model.