Home > OS >  Memory leaking while declaring viewBinding
Memory leaking while declaring viewBinding

Time:08-21

I declare viewBinding outside of the MainActivity class like this:

private lateinit var binding: ActivityMainBinding

but I'm getting a warning:

Do not place Android context classes in static fields (static reference to `ActivityMainBinding` which has field `tvTasksTitle` pointing to `TextView`); this is a memory leak

I always declared viewBinding like this in previous projects and didn't get any warnings. Of course, I can continue the project, but I would like to know the reason why. I searched the internet but couldn't find a proper answer or a workaround.

Any help would be appreciated

CodePudding user response:

Put it inside the MainActivity, not outside. If it's outside, it will last beyond the Activity, which will create a memory leak (not might, it 100% will). Also, this will cause all instances of an Activity to share the same binding. This is a bug- its possible (in fact expected) for multiple copies of an Activity to exist, and this can cause old instances of the Activity to reference the binding for a newer instance, which can cause incorrect behavior and race conditions.

The solution is just to make it a variable inside of the MainActivity class, so it's a property of the instance.

  • Related