I have an Activity
, where I initialize a class member variable in onCreate()
. In some case, I need to startActivity()
which means this Activity
turn into stopped state. When I come back, I need to use the variable.
This works OK in most phones, but I also get some crash from my users because the member become null
on their phones. This member just contains some String
and a POJO
.
Does Android clean up Activity's member variable to free up memory?
Android destroys the activity, and then recreates it. The onCreate() method gets called, and the Bundle gets passed to it.
On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.
onCreate() The Android activity lifecycle starts with the onCreate() method. This method is called when the user clicks on your app's icon, which causes this method to create the activity.
Android will generally call onPause() if you call finish() at some point during your Activity's lifecycle unless you call finish() in your onCreate() .
If screen times out on your activity, then onPause is called. After sometime if you will not open the screen then onStop will be called.
Those member variables will be cleared out if onDestroy is called, even if the activity isn't finished. You can simulate this by turning on "Don't keep activities alive" in developer settings. Once that's enabled, start your activity and then pause it (i.e. hit the home button)
To get around this, you'll need to store those member variables in onSaveInstanceState, and then restore them using the savedState bundle in onCreate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With