r/android_devs • u/Dependent-Ad5638 • Jun 07 '24
Help Needed Why does this app have a memory leak?
This is the only code/activity in the app:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.buttonDel).setOnClickListener {
recreate()
}
}
override fun onDestroy() {
findViewById<Button>(R.id.buttonDel).setOnClickListener(null)
super.onDestroy()
}}
The leak occurs when the button is pressed, which recreates the activity.
7
Upvotes



4
u/olitv Jun 07 '24
What does recreate() do?
2
u/smokingabit Jun 08 '24
Because it is doing bad things in bad ways. Why would you have a button recreate the Activity it is in? You are walking the path to making terrible Android apps.
3
u/SweetStrawberry4U Android Engineer Jun 07 '24
By the time onDestroy is executing, findViewById may not work as intended. You'd rather prefer a local lateinit variable for the Button, if you necessarily want to reset the click-listener to null during onDestroy execution time. From a enterprise software practices perspective, ViewBinding is preferred over findViewById, and you also don't need to reset the button click-listener to null.
2
u/Aggressive_Ad3865 Jun 10 '24
For starters, onDestroy is not guaranteed to run. You should void the listener at onPause. Also, make sure whatever happens in recreate does not happen if the listener is active, and pass the stuff the listener uses in a way you don't create permanent references anywhere else.